1

Jquery/Javascript event trigger does not seem to trigger the active element.

I have a play/pause button and am trying to toggle between them via Javascript. When using my physical keyboard and hit the Enter key, I see that it toggles between them. When trying to trigger it via code, it seems to not actually do anything.

A few things I have tried:

jQuery.event.trigger({type: 'keyup', which : 13});

jQuery.event.trigger({type: 'keydown', which : 13});

document.activeelement.dispatchEvent(new KeyboardEvent('keypress',{'key':'enter'}));

I would think one of these would actually act like the enter key and press the play/pause.

Any ideas?

2
  • Actual keystrokes can not be triggered in JavaScript. Instead, just initiate the action(s) that would have been initiated if the keystroke had occurred. Commented Jan 22, 2019 at 20:23
  • One thing to add, it could be any button, not just play/pause. Was wondering if there was a way to do it on document.activeelement? Commented Jan 22, 2019 at 21:50

1 Answer 1

1

For triggering a specific keypress, create a jQuery keypress Event, set which key to emulate, and trigger the created event on your DOM object, which could be your player.

var e = $.Event('keypress');
e.which = 13; // Enter key
$('#my-player').trigger(e);

As @ScottMarcus mentioned in the comment, a better idea would be to trigger the actions taken by your keypress event and not the event itself. For example, if you have the following event set:

$('#my-player').keypress(function(e) {
  if (e.which == 13) {
    togglePlayButton();
  }
});

You could instead call togglePlayButton(); directly where you'd like to emulate the keypress. Do not sacrifice code clarity just for that though.

Sign up to request clarification or add additional context in comments.

2 Comments

One thing to add, it could be any button, not just play/pause. Was wondering if there was a way to do it on document.activeelement?
@sql-noob are you looking for pressing enter and triggering the keypress event of the active element on the page?

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.