I have some simple code, but currently it does not remove the listener after the first call. How can I achieve this? Or do I really need to add redundant if/else checks on a var set upon notice?
document.addEventListener("contextmenu", function(e){
alert("Please remember this is someone's art! Give credit where it is deserved!");
document.removeEventListener("contextmenu", function(e){
console.log('User has been warned...');
});
}, false);
Updated code Still same message every right click
document.addEventListener("contextmenu", function msg(e){
alert("Please remember this is someone's art! Give credit where it is deserved!");
e.removeEventListener("contextmenu", msg, false);
}, false);
you need to pass the same function to remove as add.
the easy way to do that is to give the function a name and pass the name to removeEventListener():
document.addEventListener("contextmenu", function me(e){
alert("Please remember this is someone's art! Give credit where it is deserved!");
document.removeEventListener("contextmenu", me, false);
}, false);
see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.removeEventListener for a good overview
obligatory fiddle: http://jsfiddle.net/w1kzLkoL/
tested in chrome, firefox, and IE10
You may try this example:
document.addEventListener("contextmenu", (function() { var done = false; return function(e) { if (!done) { done = true; alert('Warning !'); } console.log('done ...', done); e.preventDefault(); return false; }; })(), false);
Open console... right click
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.