Jump to content

[SOLVED] Can I force all hyperlinks in a <div> to open in a new window?


mesh2005

Recommended Posts

yes

 

I would restrict this to javscript though...

 

give the div a unique id (if its just one div you want to do this on in a page) or a class if you have a couple of divs you want to make this happen...

 

I will use the class example...

 

<div class="external-links">

...

[links]

...

</div>

 

now the javascript...

 

window.onload = checkExternalLinks();

function checkExternalLinks()
{
var divs	=	document.getElementsByTagName('div');
var links = Array();
var i = 0;
for(var x=0; x<divs.length; x++)
{
 if (divs[x].className == 'external-links')
 {
  links = divs[x].getElementsByTagName('a');
  for(i=0;i<links.length;i++)
  {
   links[x].onclick = function()
   {
    return newPage(this);
   };	
  }
 }
}
}

function newPage(obj)
{
window.open(obj.href);
return false;
}

 

Try that...

Link to comment
Share on other sites

Im of the belief that almost NO images should open in an external window, unless that is central to the functionality of the window being opened. If I want to open a link in a new window I will (and do). But that should be my choice as the user, not the developer/designers choice.

Link to comment
Share on other sites

Thank you very much for your replies and special thanks to ToonMariner. I need to force the links for some reason, actually the site owner wanna me to do so  ;)

The Javascript code was not working correctly, I modified it. Here is the code:

function checkExternalLinks()
{
var divs =document.getElementsByTagName('div');
var links = Array();
var i = 0;
for(var x=0; x<divs.length; x++)
{
	if (divs[x].className == 'external-links')
	{
		links = divs[x].getElementsByTagName('a');  
		for(i=0;i<links.length;i++)
		{
			links[i].target = '_blank';
		}
	}
}
}

 

Thanks again

Link to comment
Share on other sites

I'm trying to get a blog link in a popup to open in a new page. I've tried every variation I can think of so that that the blog page doesn't open in the confined space of the popup. But so far, no joy.

 

I'll try the script here - but, mesh2005, is that the complete script with your corrections?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.