Created
April 27, 2009 13:23
-
-
Save noyesa/102482 to your computer and use it in GitHub Desktop.
externalLinks function causes links to outside resources to open in a new window.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * @fileoverview externalLinks function, which sorts | |
| * through all of the links on a given page, and if they are | |
| * http:, https:, or mailto: links, a class is applied and their | |
| * target is set to _blank. Also includes supporting addClass | |
| * function, which appends CSS classes to elements without | |
| * over-writing existing classes. | |
| * @author Andrew Noyes [email protected] | |
| */ | |
| /** | |
| * Adds a class to an element without | |
| * over-writing previously existing classes. | |
| * @param elem {HTMLElement} HTML element to add class to | |
| * @param newClass {String} Class to add to HTML element | |
| */ | |
| function addClass(elem, newClass) { | |
| if (!!elem.className.length) { // If className has a length | |
| newClass = " " + newClass; | |
| } | |
| elem.className += newClass; | |
| } | |
| /** | |
| * Finds all anchor elements with an href | |
| * attribute that begins with a protocol and sets | |
| * its target attribute to "_blank", causing | |
| * their target URL to open in a new window. It | |
| * then applies the protocol name as a CSS class. | |
| */ | |
| function externalLinks() { | |
| // Object detection | |
| if (!document.getElementsByTagName) { | |
| return false; | |
| } | |
| // Variable declarations | |
| var links, i, il, href, protocol; | |
| links = document.getElementsByTagName("a"); | |
| for (i = 0, il = links.length; i < il; i++) { | |
| href = links[i].getAttribute("href", 2); // Second argument ensures IE returns attribute text | |
| protocol = href.substr(0, href.indexOf(":")); | |
| if (!!protocol.length) { | |
| links[i].target = "_blank"; | |
| addClass(links[i], protocol); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment