Open a New Window

when a user click on a link, it would open a new window in HTML it is something like this:

<a href="http://google.com" target="_blank">click here</a>

How do I do this in Javascript? So a user would click on the link and it would open a new window. Here’s my code

document.writeln('<tr><td>' + "http://google.com" + '</td></tr>'); 

I know window.open(url) would open a new window, but how do I make it clickable??

Any comments or suggestion would be greatly appreciated.
thanks

You need the onclick event:

var theLink = document.getElementById('container').getElementsByTagName('a')[0];
theLink.onclick = function() {
  window.open('http://sitepoint.com');
}

The assumption there is that the link is the first or only one in a container with the ID “container”. But it of course depends on your HTML structure.

Be careful with new windows. Popup blockers are very common and you risk annoying your users when they click something and nothing appears to happen. You should either avoid new windows or warn your users that the link will open a new window.

how do I put your code in here??

document.writeln(‘<tr><td></td></tr>’);

You don’t. You just put it at the end of the body:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="container">
  <p>Here is a <a href="http://google.com">link</a></p>
</div>
<script>
var theLink = document.getElementById('container').getElementsByTagName('a')[0];
theLink.onclick = function() {
  window.open(this.href);
  return false;
}
</script>
</body>
</html>

Note that I changed the JS a bit.