Take my blog for example. I have write big posts some times and place more links. I want the user to see the links to be opened in new windows as they are still reading my pages. If the link opened in the same page, then it will be a problem to go and come back and start reading from the position they were. That won't give good experience. I want them to be stayed on my blog page and open all the links in new window. So that user is always on my blog page and if they wants then they can move across pages. It's not bad at all.
How many ways are there to implement this?
1. Make all links in web page open in new window.
2. Only some part of the web page links will be opened in new window.
I have two options: Number 1,
Open all links on the web page in new window: Default HTML supports this.
Work around:
Add this line in the <head> tag of your HTML: <base target='_blank' />
If I make all links needs to be opened in new window then home link, navigation links, search everything will opened in new window and it will frustrate user that whatever you click on the link it will open in new window. Dozens of windows in user system if you click 10-12 links. Not a good idea.
Option 2: Only specific region anchor links open in new window. This looks promising and good. But, how to. For example, in my blog, I like to open the content links only in new window.
I have a parent for all content inside a div with id='content'. Now, my goal is to add some logic to open all links in new window which are under content only.
Work around:
Add the below javascript to the <head> tag of the HTML.
<script type='text/javascript'>
//<![CDATA[
window.onload = function () {
var links = document.getElementById('content').getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
links[i].setAttribute('target', '_blank');
}
}
//]]>
</script>
This small function will do the trick. So, on window load, we are finding all the links in the particular division then adding the target='_blank' attribute to it. So, I found this is the only best solution to achieve this.
Once you add this to your page, then you will see all links inside content will open in new window and all others in the same window. This working perfectly to me. Try it on my blog by clicking on some link in the content.
If you are Jquery lover, then this is JQuery version,
$('#content a[href^="http://"]').attr("target", "_blank");
Great advantage is for blogs. All blogs needs this as there are lot of external links and other links in content. This will be the best and suitable solution.