Reputation: 24332
Let'u start with following example:
Create three pages in same directory: test.html index.html
Your test.html:
<html>
<head>
<script>
function test()
{
alert('Going to google.com?');
window.location="http://google.com";
}
</script>
</head>
<body>
<a href='' onclick="test();">google.com</a><br/>
<input type="button" value="google" onclick="test();" />
<a href='' onmouseover="test();">google.com</a><br/>
</body>
</html>
Now check test.html page on IE as well as firefox or crome.
You will notice following points:
Why?
My major interest is on 3rd point, as it even gives us alert, window.location fails.
Upvotes: 0
Views: 589
Reputation: 944198
The JavaScript event fires, window.location
is set, then the default action of the link fires and the browser goes to '', which (IIRC) resolves as the current URI.
This is the same effect you get if you click on a link, then quickly click on a different link. The browser doesn't have time to go to the first one before receiving the instruction to go to the second one, and it goes to the second one. If you delay the return of the function (by putting the alert second) it gives enough time for the request for the first URL to go through for that one to be visited instead of the second.
You would need to cancel the default action which, when you're using intrinsic event attributes (not recommended, unobtrusive JavaScript is the way forward), is done by returning false.
onclick="test(); return false;"
Upvotes: 3
Reputation: 11215
Try this:
<html>
<head>
<script>
function test()
{
alert('Going to google.com?');
window.location="http://google.com";
return false;
}
</script>
</head>
<body>
<a href='' onclick="Javascript:return test();">google.com</a><br/>
<input type="button" value="google" onclick="Javascript:return test();" />
<a href='' onmouseover="Javascript:return test();">google.com</a><br/>
</body>
</html>
Upvotes: 1