Who doesn’t use the target attribute when developing pages for the web? As we all know, usage of the target attribute is dependent on the doctype specified at the top of an XHTML document. Therefore if you wish to use this attribute it would be best to not use a strict doctypes.
The debate has been ongoing as to whether it is good practice to keep using the target attribute to open a link in a new window. There are numerous reasons for and against usage which I honestly think depends on the situation. However, should one wish to use a strict doctype and still have the ability to open a link in a new window without validation errors there are workarounds.
On a past project I was faced with a similar dilemma. The project utilized html strict doctype pages and there were sections of the project that required the links to be opened in a new window. So in order to best accomplish this the decision was made to utilize a solution incorporating jQuery.
Apart from your incorporation of the jQuery framework, all you would need to use is placed this code snippet just after the body of your page:
$(document).ready(function(){
$('a[href^="http://"]').attr("target", "_blank");
$('a[href^="https://"]').attr("target", "_blank");
});
Essentially, any link that starts with http or https will be opened in a new window.
This code snippet can be extended even further to incorporate classes or divs.
$(document).ready(function(){
$('a[href^="http://"]').attr("target", "_blank").addClass('external');
$('a[href^="https://"]').attr("target", "_blank").addClass('external');
});
As you can see I used chaining to add a class called external which I can use to maybe incorporate a link icon or even manipulate the color of that link.


Popular Posts