Home > Blockchain >  Jquery can't trigger keyup event
Jquery can't trigger keyup event

Time:03-26

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)?

CodePudding user response:

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

CodePudding user response:

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

  • Related