CHASE CHASE - 2 months ago 16
Javascript Question

JS (Jquery) .keydown event that triggers an alert

Hey everyone I am trying to figure out how to make the jquery keydown event on the entire page. In this code instance if a person presses "q" then an alert pops up saying "anything here.". But my issue is that the js I wrote seems to no work properly. Thank you.

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(window).keydown(function () {
if (event.which == 81) {
alert("TEST!");
}
});
</script>
</head>
<body>
</body>
</html>

Answer

Don't forget to pass the event into your function :)

$(window).keydown(function (event) {
  ...
});

Also, as pointed out by @praveen in the comments to OP, script order should be swapped so jquery is included before the jquery-ui script.

Comments