17 August, 2008 5:44 pm

Creating beautiful pop-ups using jquery

Posted by Richard Wong under Tutorial | 9 Comments

When it comes to pop-up windows, people don’t really associate them to being accessible and they are some what annoying. But sometimes it is necessary for whatever reason.

If you think about it, a link that opens up a new window is one of the most simple thing you can do with javascript & HTML. There is no reason for it to be ugly.

This is the old fashion and totally wrong way of doing it:

<a href="javascript:window.open(http://www.popup.com/);">Popup link</a>

Why? The a tag is not linking to a link but instead it is running some javscript. That means the whole meaning of the link is gone.

Here is what an accessible and clean link looks like:

<a href="http://www.popup.com" rel="pop-up">Open a Popup</a>

In this version, there is no inline javascript which is always a good pratice to separate HTML and javascript. It keeps everything simple and clean. The addition of the rel attribute is used to describe the relationship between the current page and the href destination of the anchor.

Now we have this beautiful HTML link. It is time to do some magic with javascript and jQuery.

( function popup() {
        $( document ).ready( function() {
                $("a[rel='pop-up']").click(function () {
                    var features = "height=700,width=800,scrollTo,resizable=1,scrollbars=1,location=0";
                    newwindow=window.open(this.href, 'Popup', features);
                    return false;
                });
        } );
}() );

This is a very simple javascript using jQuery. Basically, the code is looking for all the links with the rel attribute and assign a onclick event to open the pop-up window. Of course, there are different ways to abstract the above code to make it more flexible. But the idea is to have beautiful pop-up link and have the javascript to do the work later.