Recent XHTML standards have depreciated the use of the target attribute for controlling link targets. Pages containing this attribute will no longer validate. The reasoning is that modern browsers give the user the ability to open links wherever they want and that web developers should leave the decision up to the reader. While I don’t completely disagree with that philosophy, I choose not to send my visitors away when sending them to other sites. As a courtesy, you might consider notifying readers whenever a link opens a new window. To get around the limitations imposed by the new standards, you can use a JavaScript to target your links. This prevents hard coding the target attribute into your page. The validator is happy and your links still target wherever you want them to. The JavaScript that performs this task is actually pretty simple. To begin, you need to create a function and gather all of the links on your page. /*<![CDATA[*/ function outboundLinks() { if (!document.getElementsByTagName) return; var anchors = document.getElementsByTagName("a"); The first line of the function checks to make sure that the getElementsByTagName function is supported by the current browser. If it isn’t, the function simply exits before any errors are generated. The second line searches the document tree for any link elements (<a>) and returns those objects as an array. for (var i=0; i<anchors.length; i++) { var anchor = anchors[i]; if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "nofollow") { anchor.target = "_blank"; } Next, a "for" loop iterates through each of the array elements and checks for any links that contain both a valid destination and a rel=”nofollow” attribute. It also adds the target attribute that we need. Because of our Wordpress plugin, this code will only change external links (since they are the only ones with the rel=”nofollow” attribute. } } window.onload = function() { if (document.body) outboundLinks(); }; /*]]>*/ Finally we close our function and add it to the document’s onload event, so that it is executed whenever the page is fully loaded. Save this file as external.js and upload it to your web site.
blog comments powered by Disqus |
|
|
|
|
|
|
|