Friday, February 13, 2009

Opening links in a new window

Like it or not, people often expect certain documents (i.e. PDFs) to open in a tab or window. Often enough, the ugly solution of target="top" or similar is used otherwise JavaScript is employed to redirect links. Both methods are a wonderful source of confusion and annoyance.


With this in mind, I cobbled together my own solution employing the wonders of jQuery to handle the selectors:


$(function(){
$("a[href$='.pdf']").click(function(e){
//don't interfere with modifier keys
if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) {
return true;
}
window.open($(this).attr("href"));
return false;
}).attr("title", function(){
return this.title + " (Opens in a new window)"
});
});

Two key things happen here: modifier keys are left alone so power users are happy and the anchor”s title is altered to give users a hint of what’s going on.

2 comments:

Running my own race said...

Wow this went over my head! Very technical :-)

Running my own race said...

Wow very technical, went over my head :-)