views:

31

answers:

2

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:

  1. Button works perfectly.
  2. First hyperlink works differently in IE and other browser. In IE, it brings us back to index.html page, while in firefox, it stays on same page.
  3. For first hyperlink, window.location fails.
  4. Second hyperlink you cannot click on that, as mouse over event will fire first, and it works perfectly!

Why?

My major interest is on 3rd point, as it even gives us alert, window.location fails.

+1  A: 

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>
ITroubs
Why do you have labels before your return statements? https://developer.mozilla.org/en/JavaScript/Reference/Statements/label
David Dorward
If I put `alert()` after the `window.location`, then `alert()` will be called first, then it redirects us to our location why?
Vikas
actually i am not that experienced in js to tell you why alert comes before the redirect. to me it seems like the redirect is triggerd on the change of the location property of the window object and that the event is put on a stack and being processed after the click event that is now being processed in your test() method
ITroubs
+2  A: 

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;"
David Dorward