Max Williams
Max Williams

Reputation: 32933

Jquery can't trigger keyup event

I'm using jquery in a web app. I have a page which is listening for keypresses like this:

  document.addEventListener('keyup', function (event) {    
    event.preventDefault();
    var key = event.keyCode;
    console.log("pressed key "+key);
  });

That works in terms of me pressing keys - it outputs the key code to the console.

I now want to simulate a key press with a different function, which i'm doing like this:

  var keycode = 27;
  $(document).trigger(
    jQuery.Event( 'keyup', { keyCode: keycode, which: keycode } )
  );

But, nothing happens - specifically, i don't see the console log from the first function.

Can anyone see my mistake?

EDIT: it works if I change the first function to use jQuery .on() rather than native js .addEventListener, but i'd still like to understand why. Is document a different entity to $(document)?

Upvotes: 1

Views: 647

Answers (2)

Sarah Vela
Sarah Vela

Reputation: 144

To address the edit, when you select an element using the jQuery $() notation it selects it as a jQuery object with lots of jQuery methods available. Using the vanilla JavaScript document selector will create a DOM element, but not a jQuery object. This page has more info on alternative ways to make jQuery objects when needed: http://jqfundamentals.com/chapter/jquery-basics

Upvotes: 1

Pietro Teggi
Pietro Teggi

Reputation: 124

Jquery have a function that you can bind at your eventlistener .keyup(). You can read the full documentation here: https://api.jquery.com/keyup/

Upvotes: 0

Related Questions