JavaScript JavaScript - 6 months ago 29
Javascript Question

Right click acts like a left click on the event

I have this code:

document.getElementById("1").oncontextmenu = function() {
return false
}


It disables the little window that shows after a right click (only on the button/image).

On my code (https://jsfiddle.net/nnuyguat/) everything is working fine, except for when I do a right click on the image as it triggers the left click event and changes the image untill I move the mouse.

Another related problem is if I press left click without releasing and then right click (releasing the right button), it will also change the image.

I need to prevent the image changing with right clicks. It should work as the closing button of the browser (except it's another images and it doesn't close anything).

Answer

The right click event is not triggering a left click. It is just activating your object. Your image says "click" but it is inaccurate. It should say "Active".

Second, a number is NOT a valid ID. So rename your div from id="1" to id="one" or similar.

Finally, try with this code, instead of yours:

document.getElementById("one").addEventListener('contextmenu', function(ev) {
    ev.preventDefault();
    alert('hello from right click');
    return false;
}, false);

See https://jsfiddle.net/nnuyguat/3/

Comments