Onkeydown not working javascript - Stack Overflow

Here is my codedocument.onkeydown = function (a) {if (a.which == 13) {alert("Not Anymore");}

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

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

Share Improve this question edited Sep 14, 2015 at 3:36 Tushar 87.2k21 gold badges163 silver badges181 bronze badges asked Sep 14, 2015 at 3:31 Duncan MilradDuncan Milrad 411 gold badge1 silver badge4 bronze badges 2
  • 2 The event handlers are overriden by the last, so only the last works – Tushar Commented Sep 14, 2015 at 3:33
  • document.addEventListener(); would be another option. – Sebastian Simon Commented Sep 14, 2015 at 3:39
Add a ment  | 

1 Answer 1

Reset to default 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);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742410430a4438701.html

相关推荐

  • Onkeydown not working javascript - Stack Overflow

    Here is my codedocument.onkeydown = function (a) {if (a.which == 13) {alert("Not Anymore");}

    10小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信