Converting links to popups using javascript

I 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 :-)

Related posts

Comments

Add comment