Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right click stop propagation

Tags:

javascript

How do I stop the propagation for right click events in javascript, so parent elements do not detect them at all? When I click the link in the following html, left clicks are not detected, but right clicks are detected by the document element as 'click' events instead of 'contextmenu' events. I've tried to attach event listeners to mousedown, contextmenu, but to no success.

[EDIT] Changing the code to contextmenu works on chrome but not firefox (v23.0.1), this is probably a firefox bug.

<!DOCTYPE html>
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="application/javascript;version=1.8">

function log(s){
    document.getElementById('log').innerHTML+=s+'<br/>';
}

window.onload=function(){
    document.addEventListener('click',function(e){
        log('click detected');
    },false);

    let link=document.querySelector('a#link');
    //click only cares about left clicks
    link.addEventListener('click',function(e){
        e.stopPropagation();
        return false;
    },false);
};

</script>
</head>

<body>

<a id="link" href="javascript:void(0);">Link</a>

<div id="log"></div>

</body>
</html>
like image 647
simonzack Avatar asked Oct 20 '25 21:10

simonzack


1 Answers

The 'right click' event is called the 'contextmenu' event.

http://www.quirksmode.org/dom/events/contextmenu.html


Example:

<!DOCTYPE html>
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script>

function log(s){
        document.getElementById('log').innerHTML+=s+'<br/>';
}

window.onload=function(){
        document.addEventListener('click',function(e){
                log('click detected');
        },false);

        document.addEventListener('contextmenu', function(e){
                log('right-click detected');
        }, false);

        var link=document.querySelector('a#link');

        link.addEventListener('click',function(e){
                e.stopPropagation();
                return false;
        },false);

        link.addEventListener('contextmenu',function(e){
                e.stopPropagation();
                return false;
        },false);
};

</script>
</head>

<body>

<a id="link" href="javascript:void(0);">Link</a>

<div id="log"></div>

</body>
</html>
like image 95
Lee Kowalkowski Avatar answered Oct 23 '25 11:10

Lee Kowalkowski