2

I am in debug mode, so I can see which page is being hit.

When I call either window.location or window.location.replace(..) it goes to the page, but then back to the originating page!

How could this be??

The solution was to add:

    window.location.replace(...);

    return false;

Why does return false make this work properly now?

palswim
  • 11,856
  • 6
  • 53
  • 77
Blankman
  • 259,732
  • 324
  • 769
  • 1,199

1 Answers1

4

If this script happened on an onclick or onsubmit event, then no return or returning true will indicate that the browser should take the default action for the link/form. So, if you had an onclick handler like:

<a href="http://www.google.com/" onclick="window.location = 'http://www.yahoo.com/';">

Then the browser will go to Yahoo, then see that it should execute the link's other action (navigating to Google). When you indicate return false;, the browser knows not to execute the next/default action.

<a href="http://www.google.com/" onclick="window.location = 'http://www.yahoo.com/'; return false;">

So, why does return false; make this work?

For any event hander, to return true indicates to continue as normal and to return false means to stop trying to handle the event (prevents default handling and stops propagation), though there are arguments against using return false;.

Community
  • 1
  • 1
palswim
  • 11,856
  • 6
  • 53
  • 77
  • +1. If the element clicked on had '#' as its `href`, then it'll change location, then go back to the starting page. Returning false stops the default behaviour. – Skilldrick Sep 09 '10 at 16:32