Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: window.location.href doesn't redirect when calling function within a function

Tags:

javascript

window.location.href redirects the browser to stackoverflow.com when the button is clicked, but does not when hitting "Enter" in the input textfield, despite both event listeners using the same function visitStack.

If this helps, changing the form tags to div tags somehow makes it work, but it's not semantic, of course.

Changing "keydown" in the last line to "click", and moving visitStack(e) immediately within keyDownTextField(e), make it work too.

So keydown and/or form tags seem to be the culprits here, but I'm not sure.

<form>
<input id="iamtext" type="text" />
<input id="gobutton" type="button" value="Overflow" />              
</form>


<script type="text/javascript">
    document.getElementById("gobutton").addEventListener("click", visitStack, false);

    function visitStack(e) {
        e.stopPropagation();                
        window.location.href = "http://www.stackoverflow.com";
    }

    function keyDownTextField(e) {
        var keyCode = e.keyCode;
        if(keyCode==13) {
            alert("Entered!");
            visitStack(e);
        }
    }

    document.getElementById("iamtext").addEventListener("keydown", keyDownTextField, false);
</script>
like image 730
chimerical Avatar asked May 13 '26 07:05

chimerical


1 Answers

Hitting ENTER in a text input field in an HTML form has rather different effects on different browsers.

In your case, I assume that the form is submitted on hitting ENTER. Since you haven't specified any action, the form is submitted to same page leading to a reload.

like image 74
Amarghosh Avatar answered May 15 '26 19:05

Amarghosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!