Tuesday, July 30, 2013

How to Open Anchor Links in a New Window using Javascript

Add code below 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>

on window load, we are finding all the links in the particular division then adding the target='_blank' attribute to it.
So, I this is a good solution to achieve this. Once you add this to your page, then you will see all links inside element that contain "yourcontent" ID 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.
Disqus Comments