Thursday 20 June 2013

jQuery Window Handler (target="_blank")

I love jQuery. I make no bones about it - it's been a revelation for many developers who want to utilise code blocks as reusable elements and by golly it does speed up development both client-side and server-side!

However there are occasions when the traditional view on using "legacy" HTML is sometimes the only way we can perceive a solution. Take this example - we had a colleague who was at his wits end as he'd spent ages trying to use the good ole image map for a map of Scotland to make a clickable map for guest houses. All very well and easy to do. Problem was that the code used another jQuery handler to overlay a replacement map of the area clicked to make it look pretty which in turn played havoc with the internal target="_blank" directive.

After much swearing he dropped me a note to see if we could help. We took a look at the code and it all seemed fairly ok and we encountered the same problem, wtf was going on here, we couldn't use the traditional means above nor could we see how the href wasn't being looked at by the jQuery function.

After much looking and wondering (god bless Stack Overflow, by far one of the best troubleshooting websites ever) we pulled together a code block which may suit one or two others who have need of it.

Image Map Code:

<map name="mymap" id="map">
<area coords="6, 234, 17, 235, 35, 205, 37, 22, 44, 163, 56, 152, 76, 122, 82, 115, 80, 91, 66, 83, 28, 183, 25, 137, 22, 151, 7, 160, 7, 179, 16, 181" class="newWindow" href="#" rel="http://www.bbc.co.uk" id="12" shape="poly" alt="altname" title="title" />

</map>

We added the class to the area to make it a little easier to pass into the jQuery function

jQuery:

$('.newWindow').click(function(e){
e.preventDefault();
var url = $(this).attr('rel');
window.open(url, "_blank");
return false;
});

So, basically, breaking down the code the following happens:

$('.newWindow').click(function(e){ //render a new function each time the class newWindow is clicked

e.preventDefault(); //stop any links from working (note this could probably be left out, we kept it in for convenience)

var url = $(this).attr('rel'); //create a variable "url" from the rel value on the area

window.open(url, "_blank"); //good ole JS to handle the window event

return false; //stop other shit from happening

So, in summary, the little function allows image maps to open URLs in a new window by making the existing link a # (null) link and placing the URL into the rel tag. Grabbing the rel tag into the url variable we push that into the window.open event and voila the target="_blank" emulator kicks in.

There are probably numerous ways of doing this but I thought this may help some poor troubled soul out!

Scripts pooled from various links including

http://stackoverflow.com/questions/4813879/window-open-target-self-v-window-location-href

http://stackoverflow.com/questions/970388/jquery-disable-a-link

No comments:

Post a Comment