Converting links to popups using javascript
Published on 07. January 2008 inI was asked today how I would go about looping through an html page and attach an onclick event for all links with a certain class. So I decided to make an example and post it here.
What I am going to do is mark all links that should function as a popup window with the class "popup", and then I am going to intercept the click event on those links by using unobtrusive javascript.
Here it goes. The html markup we will use looks like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>Untitled Page</title> <script type="text/javascript" src="addpopuplinks.js"></script> </head> <body> <p>This is a text with a few links in it. <a href="http://www.google.com/">This is a regular link</a> which just goes to a new webpage. <a class="popup" href="http://www.umbraco.org/">This is marked with a class "popup"</a> and will recieve a javascript onclick event when the document is loaded.</p> </body> </html>
And the javascript looks like this:
//Add multiple functions to the window.onload event.
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
oldonload();
func();
};
}
}
//Add the onclick event to link of a certain class
function makePopupLinks() {
//Check that browser supports the used methods
if (!document.getElementsByTagName) { return false; }
//Get all links in document
var links = document.getElementsByTagName("a");
//Loop through links
for (i = 0; i < links.length; i++) {
//Check for the right classname
if (links[i].className == "popup") {
//Add the onclick event to the object/element
links[i].onclick = function() {
window.open(this.getAttribute("href"), "popupwindow", "width=400,height=400");
//Return false so that the link is not followed in the main window
return false;
}
}
}
}
addLoadEvent(makePopupLinks);
The comments in the code should be more or less self explanatory but if you have any questions, feel free to post a comment :-)

On 12. January 2009 by Jayesh
But make a not of this that this code will only pick those links element those are immediate to Body (Document) and not ones which are inside some other elements.
For instance if we have some link inside <a href.... this will not be loaded and converted into popup link!! For this we need to collect individual element and execute document.getEle... on that element.
On 12. January 2009 by Morten Bock
I'm not sure what you mean. Are you putting A elements inside other A elements?
The document.getElementsByTagName gets all elements in the document, so I don't see where you would need to collect other elements... Could you clarify?