08 March 2010

Why did I use jQuery to open links in a new window?

To make my XHTML pages validate, of course. Using a plain old 'target=blank' in links isn't allowed any more, is it? Every web developer seems to have an explanation or a workaround for the problem but, honestly, I've given up trying to understand what the fuss is about.

I agree that page validation is a useful exercise but this is such a small issue, I was tempted to just ignore it. Honestly, if 'target=blank' is your only validation error, who's going to care? Well, the reason I did care was that the links in question were in the master page which meant they showed up on just about every page on the site. Always getting that silly red light on my status bar makes it a lot harder to tell if there's anything else wrong with each page. Something that really matters, something that might break the page come the next browser release. In the long run, it's easier to fix the links than put up with the errors.

So what did I do about it? Out of the many options I could choose from, I started with jQuery because it makes everything pretty simple and we were already using the library anyway. I used a 'rel=external' attribute to mark the links that should open new windows, as suggested by a bunch of sites. It feels semantically correct even though external isn't one of the values defined by the W3C. Next, the jQuery selector dynamically adds 'target=blank' back into the links. As you'd expect, the browser does the right thing, including opening the link in the same window if scripting is disabled. (If you don't allow scripting, I suppose that's the behavior you expect to see.)

If you get the impression we're pretending to fool the validator while it looks the other way and pretends it didn't see anything, then you've got the right idea. Still, now I've got green lights all the way and that's really what I was looking for.

No comments: