0

I am trying to test in jasmine and need to trigger a keyup event with a specified keycode (enter in my case). When i try this

document.getElementById('title').addEventListener('keyup', function(e){
    console.log(e.keyCode);
});
var e = $.Event("keyup", {keyCode: 64});
$('title').trigger(e);

the event is not being triggered, although when I do manually set focus on it and press it is being triggered

but when i try this

$('title').on('keyup', function(e){
     e.currentTarget.style.color = 'red';
     console.log(e.keyCode);
});

var e = $.Event("keyup", {keyCode: 64});
$('title').trigger(e);

it is being triggered. I dont understand why one is not working and the other one is

13
  • First line of the .trigger() doc: "Any event handlers attached with .on() or one of its shortcut methods are triggered when the corresponding event occurs." Commented May 20, 2019 at 14:02
  • missing the event parameter: ...('keyup', function(e){ Commented May 20, 2019 at 14:03
  • i dont understand, can you clarify Commented May 20, 2019 at 14:06
  • first line should be: document.getElementById('title').addEventListener('keyup', function(e){ Commented May 20, 2019 at 14:06
  • 2
    Again: .trigger() only triggers event listeners that were added using a jQuery function. It won't trigger listeners added using addEventListener Commented May 20, 2019 at 14:10

2 Answers 2

2

If you use addEventListener don't use trigger, use dispatchEvent :

document.getElementById("q").dispatchEvent(new KeyboardEvent('keyup', { 'keyCode': 65 }));
Sign up to request clarification or add additional context in comments.

Comments

0

.trigger() only works when the event handler is attached using jquery. It doesn't work on native event listeners.

In the second case, you're attaching with $(..).on So jquery will trigger that event. Native Event Listener won't work here. You can use dispatchEvent

var event = new KeyboardEvent("keyup", {keyCode: 64});

document.getElementById('title').addEventListener('keyup', function(e){
    console.log(e.keyCode);
});

document.getElementById('title').dispatchEvent(event);

Check here for more info https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events

2 Comments

its logging undefined
Give it a try now.

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.