简体   繁体   中英

Unable to trigger events in jQuery

I want to trigger a context menu event in jQuery on a audio element. Here is the code:

$("audio").contextmenu();

However, this does not show a context menu for the element. I thought maybe there is need for some user interaction so I wrapped it in a moueenter event.

$("audio").on("mouseenter", function(e) {
   $(this).contextmenu();
}

However, the context menu still does not appear. Finally, I decided to do the right click on the audio element manually and trigger a key press event but it also did not seem to do anything.

$("audio").on("contextmenu", function(e) {
  var code = 86;
  $(this).trigger(
    jQuery.Event( 'keydown', { keyCode: code, which: code } )
  );
});

This code snippet was supposed to trigger a jQuery keypress event with "v" pressed.

When we right click on an audio element and press "v", it shows a save audio as dialog. I wanted to write the code to trigger the context menu and keypress programatically but none of them seem to have any effect. Why is that?

You can trigger the right click menu on your audio element but only if you right click on it. Be sure to add the 'controls' attribute to your audio element so that there would be something to click on. Try it on the code below.

 $("audio").on("contextmenu", function(e) { alert("Hello Context Menu!"); }); $("button").on("click", function(){ $("audio").contextmenu(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <audio id="t-rex-roar" controls src="https://soundbible.com/mp3/Tyrannosaurus%20Rex%20Roar-SoundBible.com-807702404.mp3"> </audio> <button>Call Context Menu Event for Audio Element, Event only</button> 

However , you can't add a button click event that displays the context menu for another element; Programmatically Calling Browser Right-Click Menu Options?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM