Reputation: 131
I have to have separate javasvript and html-files and I'm trying to open a new window when I click on a link, but it is not working.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
<link rel="stylesheet" href=""/>
<script type="text/javascript" src="java3.js"></script>
</head>
<body>
<a href="#" id="link">Click!</a>
</body>
</html>
Javascript:
var a = document.getElementById("link");
a.onclick = function(){
window.open("http://www.google.com");
};
Upvotes: 0
Views: 57
Reputation: 57703
If you open the console you will likely see an error message like:
TypeError: Cannot set property 'onclick' of null
This is because document.getElementById("link")
is null
.
Why is it null
? It's right there on the page!
Well, not when this code runs. The JavaScript code runs before the body is defined.
Either move your script down, or wrap your code in a ready/onload event:
window.onload = function() {
var a = document.getElementById("link");
a.onclick = function() {
window.open("http://www.google.com");
};
};
Upvotes: 3