jQuery XHTML Strict Target=”_blank” Solution

As many of you know, XHTML Strict does not allow the target attribute within <a> tags. I have been using a JavaScript solution which I found online a few years back. The code was a bit verbose so I decided to update it using jQuery.

$(document).ready(function () {
    $('a[rel="external"]').each(function(i) {
        $(this).attr('target', '_blank');
    });
});

With the above code in place, simply put rel=”external” on any anchor tags that need to open in a new window.

Prompt Users to Save Changes

Want to be able to prompt users if they have unsaved data and they close out the browser? Unfortunately, I’ve yet to find a cross browser solution but in Internet Explorer and Firefox the onbeforeunload event gives you just that ability. The event will fire when a user closes the browser or when a user navigates to a different URL. Simply have the function assigned to the event return the string you wish to display to the users.

window.onbeforeunload = function() {
    if(window.event.clientX < 0 || window.event.clientY < 0)
        return "You have unsaved changes. Are you sure you wish to leave this page?";
}

The above code is setup to only work on the browser or tab close button. Remove the if statement if you want it to work when a user navigates away from the page.