3

Here is my code

document.onkeydown = function (a) {
    if (a.which == 13) {
        alert("Not Anymore");

    }
}

document.onkeydown = function (b) {
    if (b.which == 65) {
        auto();
    }
}

document.onkeydown = function (c) {
    if (c.which == 83) {
        auto2();

    }
}

Only the last snippet works can someone explain why this is happening check my website and you can see it isnt working when you press a but when you press b it is

Thanks, I appreciate the help and feedback

2
  • 2
    The event handlers are overriden by the last, so only the last works Commented Sep 14, 2015 at 3:33
  • document.addEventListener(); would be another option. Commented Sep 14, 2015 at 3:39

1 Answer 1

5

You're binding the same event on the document multiple times. So, the later event handlers override the previous event handlers just like the functions with same name does. You need to bind only one event handler and use if... else in it.

You can use this

document.onkeydown = function (e) {
    if (e.which == 13) {
        alert("Not Anymore");
    } else if (e.which == 65) {
        auto();
    } else if (e.which == 83) {
        auto2();
    }
};

Also, use addEventListener instead of onkeydown.

document.addEventListener('keydown', function (a) {
    if (a.which == 13) {}
    ...
}, false);
Sign up to request clarification or add additional context in comments.

2 Comments

To expand on this, nowadays its a common best practice to use event listeners; document.addEventListener('keydown', function(e){})
@DuncanMilrad You're welcome! If your problem is solved, kindly accept the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.