This topic is quite a challange because on one side I want my websites "strict" valid. On the other hand, sometimes it's important (at least clients say so) to open links in a new window, so I did a little research (and there are a lot of informations out there to this problem)
What are the solutions for being valid and in the same time opening links in a new window?
1. I tried it with CSS: (I know, I know... CSS is for styling only, not for behavior.. I'm searching solutions right now)
Theoretically it can be done with CSS3. According to this page the code should look like this:
a {
target-name: new;
target-new: tab;
}
But none of the browsers responded to it so this solution is precluded.
2. Javascript:
Here we have quite interesting solutions.
Manually open a new window with "window.open(URL)":
Inline mode:
<a href="http://thinkrement.blogger.com" onclick="window.open(this.href); return false;">Read Thinkrement!</a>
This works, however it's not so elegant and it's better to keep the HTML and Javascript seperate.
So, let's improve it a bit:
HTML:
<a href="http://thinkrement.blogger.com" rel="popup">Read Thinkrement!</a>
Javascript:
window.onload = function() { var links = document.getElementsByTagName('a'); for (var i=0;i < links.length;i++) { if (links[i].rel == 'popup') { links[i].onclick = function() { window.open(this.href); return false; }; } } };
or with jQuery:
$('a[rel="popup"]').click(function() { window.open(jQuery(this).attr("href")); return false; });
The constrained method:
With Javascript it's similar to the previous "window.open" method with the difference, that instead of "window.open" we use:
window.onload = function() { var links = document.getElementsByTagName('a'); for (var i=0;i < links.length;i++) { if (links[i].rel == 'popup') { links[i].target="_blank"; } } };
This is quite simple, however this solution is not supported by IE and Chrome.
With jQuery it a bit easier (only 1 line):
$('a[rel="popup"]').attr("target", "_blank");
3. HTML:
- Use a Transitional Doctype
- Have some "target" errors on your site
- or put it out of your mind that you want to use the target attribute. It is said that for usability reasons it's better to let users decide whether they want a new window (tab) or not.
No comments:
Post a Comment