Tutorials

It's more than just pretty pictures. A great site has semantic code and good content. Let me help you turn your design into a great site. Learn more

Opening Links in a New Window with a Strict Doctype

Before I even had a design ready for this site, I knew that I'd be using a strict doctype. I also knew I'd run into small validation errors on links that need to open in a new window because target="_blank" or target="new" doesn't validate with a strict doctype. To fix this problem, I've written a tiny bit of code so that I can have my cake and eat it too.

There are two versions of this script, one for mootools and one for jQuery. If you don't use either one of these libraries then I think this short explanation is enough for you to rewrite one using the library of your choice or from scratch.

Both scripts do the same thing, they search and find all anchor tags on the page that has the class name newWindow and when clicked adds the target attribute and sets it to blank.

Mootools

window.addEvent('domready', function() { $$('a.newWindow').addEvent('click', function(){ $$('a.newWindow').setProperties({ target: '_blank' }); }); });

jQuery

$(document).ready(function() { $('.newWindow').click(function(){ $('.newWindow').attr({ target: '_blank' }); }); });

I've tested this in Firefox (mac/windows), IE6, IE7 and Safari (mac/windows) and it works perfectly. Unfortunately, I do not have time to debug problems for everyone. If you're trying to customize this script even more then I would strongly suggest looking at the documentation for both mootools and jquery.

posted Mar 23, 05:47 PM |

1 | On Apr 28, 06:23 PM mark said...

I feel that both your MooTool and JQuery methods should use the “domready” event rather than the “window”.onload one as the links will not be able to open in new windows before the images are loaded with onload.

window.addEvent(‘domready’, function(){…});

2 | On Apr 29, 08:00 AM Toya said...

@Mark you make a good point. I hadn’t thought of that and you’re right. I’ll change it. Thanks!!

commenting closed for this article

Recent Tutorials

Categories

Mootools/Moo.fx Tutorials