Page 1 of 1

Replacing target=_blank in XHTML new way that is popup blocker friendly Rate Topic: ***** 1 Votes

#1 bizzehdee  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 5
  • View blog
  • Posts: 54
  • Joined: 06-April 08

Post icon  Posted 24 May 2008 - 12:38 PM

target=_blank has been removed from xhtml, so you can no longer do the following.
<a href="http://www.bizzeh.com" target="_blank">bizzeh's portfolio</a>


so what you must do now is use a piece of javascript to mimic the functionality of target=_blank

step 1. create a file named xhtmltb.js and place the following code in it.
function externalLinks() {
  //we need getElementsByTagName for this to work
  if (!document.getElementsByTagName) return;
  
  //get all the anchors within the document
  var anchors = document.getElementsByTagName("a"); 
  for (var i=0; i<anchors.length; i++) { //loop through all the anchors
	var anchor = anchors[i]; 
	
	//check to make sure that we have a href, so its a real hyperlink
	//and make sure that we have a ref and its set to external
	if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external") {
	
	  //assign the dynamic function to the onclick event.
	  anchor.onclick = function(x) {
		//store the variable so that we can actually use it within each function
		var p = x;
		return function() {
		  var w = window.open(p); //try and open up a new window with the url
		  if(!w) { //check to see if the window opened
			//let the user know that a window didnt open
			alert("A popup blocker seems to have blocked the window from opening");
		  }
		  
		  //return false to make sure the browser doesnt navigate away in the current window also
		  return false;
		}
	  }(anchor.getAttribute("href")); //pass through the href for this anchor
	}
  }
} 

//make sure we only set everything up on load
//after the DOM has been inited
window.onload = externalLinks;

step 2. place it in the same directory as your html files
step 3. add the following code into the head part of your html file
<script type="text/javascript" src="xhtmltb.js"></script>

step 4. add rel="external" to the anchor link, e.g.
<a href="http://www.bizzeh.com" rel="external">bizzeh's portfolio</a>


now you will notice that when you click on the links that have rel external, open up in a new window. though, this version will detect a window that did not open, due to a popup blocker and warn the user that the window did not open.

Is This A Good Question/Topic? 0
  • +

Page 1 of 1