views:

104

answers:

2

I face a curious problem with redirection...

Look at this small example: it works only if I add the alert() call after the redirection sentence! If I remove the alert() it does not work anymore!!!

Any idea why (I'm using Firefox 3)?

Thanks.

<html>



<script type="text/javascript">

function GotoPage() { 

    location.href = "http://www.yahoo.com";

    // Without this alert redirection does not work!!! 

    alert("Hello!"); 

}

</script>



<body>

    <form>

    <button onclick="javascript:GotoPage()">Go</button>

    </form>

</body>



</html>
+2  A: 

Not sure, but I suppose that, if you don't return false in your onclick handler, the default action of the button is executed -- and that is not redirecting.

The alert freezes the browser long enough so the redirection is made before the control is given back to the default behavior of the button element.


Try using something like this :

<button onclick="GotoPage(); return false;">Go</button>


Or try modifying the function so it returns false :

function GotoPage() { 
    location.href = "http://www.yahoo.com";
    return false;
}

And return,in your onclick handler, what the function returned :

<button onclick="return GotoPage();">Go</button>


BTW : no need for the javascript: part.

Pascal MARTIN
Pascal,Many thanks! The first option solved the problem (the others don't)!!But I'm still curious about why adding the alert() call makes it work???Anyway, thanks again!Best regards,
Jose M Balaguer
You're welcome :-) ;;; the alert is preventing the browser from executing the default action of the button element *(at it prevents the function from ending, returning control to its caller)*. location.href, on the other hand, is assigned before the alert, so it's being executed.
Pascal MARTIN
A: 

I believe you should set window.location, not location.href.

function GotoPage() {
    window.location = "http://www.yahoo.com";
}
Jakob Kruse
Jakob, Thanks!!! but your solution doesn't work... :-(
Jose M Balaguer
Actually neither. You should specify both that the location object is in the window object (to elliminiate naming conflicts) and that it's the href property that you want to set (as some browsers won't work with assigning the URL to the location object directly). So you should use `window.location.href`.
Guffa