Window.location.href and Executing Code Placed after
by John Ryding
This is the type of situation where you don’t even know HOW to word it for google to search for the answer. But anyways…on to the situation:
You have run into a situation where you need to change your web page’s URL. Simple enough, all you need to call is the following:
window.location.href = "http://google.com";
Now consider a situation where you have to check that a certain situation is met AFTER you change the URL of the page. Or you just have code that is written after window.location.href is changed in the function. Does the code after the change get executed?
Yes. It does.
Consider the following function:
function test()
{
window.location.href = "http://www.google.com";
var strings = "cool!";
window.location.href = "http://www.gamefaqs.com";
alert( strings );
}
If you run this code, the web page does not end up at google.com, but rather at gamefaqs.com. Before that transition even occurs though, an alert box pops up saying “cool!”.
To prevent this situation from creating a problem for you, and end up at google.com, we want to end the function and stop the code from being executed:
function test()
{
window.location.href = "http://www.google.com";
return;
var strings = "cool!";
window.location.href = "http://www.gamefaqs.com";
alert( strings );
}
Now your page will end up at Google, and no alert box appears.
Comments
Cool!