Wednesday, June 27, 2012

Open all anchor links in new window

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.

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.
 <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>

If you are in Jquery , then this as,
$('#content a[href^="http://"]').attr("target", "_blank");

No comments:

Post a Comment