Bruno
Bruno

Reputation: 9077

eventListener not catching keypress event with Javascript

I've written some code to check if a user launches a search on Google (clicking on the Search button or typing Enter).

My code works fine (it's a Firefox extension) except I can't get the code of the key pressed for an unknow reason.

my code :

window.addEventListener("submit", function() { myExtension_with_click.init(); }, false);
window.addEventListener("keypress", function() { myExtension_with_keypress.init(); }, false);

var myExtension_with_click = {
    init: function() {          
         alert("This works");
    }
}

var myExtension_with_keypress = {
    init: function() {
             alert("This works")
             if (window.event.keyCode == 13) {
                 // This doesn't work
                 alert("This doesn't work");
             }
    }
}

Upvotes: 0

Views: 2247

Answers (2)

Bruno
Bruno

Reputation: 9077

A simple solution is to use the event "change" in the event listener !

Upvotes: 0

Pratik
Pratik

Reputation: 30855

try this it works

<html>
<head>
<script>
    window.addEventListener("submit", function() { myExtension_with_click.init(); }, false);
    window.addEventListener("keypress", function(event) { myExtension_with_keypress.init(event); }, false);

    var myExtension_with_click = {
        init: function() {          
             alert("This works");
        }
    }

    var myExtension_with_keypress = {
        init: function(event) {
                 //alert("This works")
                 if (event.keyCode == 13) {
                     // This doesn't work
                     alert("This doesn't work");
                 }
        }
    }

</script>
</head>
<body>
    <input />
</body>

Upvotes: 1

Related Questions