Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right mouse click detection on SVG shape in JavaScript not working


I need some help with my script in which I would like to detect RMB click.
INFO: finally I want to display my own right-click menu on a dedicated SVG shape, which is displayed with a use of Raphael js lib, I found out that there are many different examples on web, even very simple ones to implement, like with jQuery - but I have to be able to detect wether RMB was clicked or any other.
I have tried (without success on RMB) a following peace of code:

<html>
<head>
    <script type="text/javascript" src="raphael.js"></script>
    <script>
        window.onload = function() {
            var paper = new Raphael(document.getElementById('canvas_container'), 300, 300);
            var shape = paper.path('m150,150l40,0l0,20l-40,0l0,-20z');
            var fill=shape.attr({fill:'#FFFFFF'});
            fill.click(function (evt){
                if(evt.button == 2) {
                    // right mouse button pressed
                    evt.preventDefault();
                }
                alert("Pressed mouse = " + evt.button.toString());
            });
        }
    </script>
</head>

<!--    <BODY oncontextmenu="return false"> -->
<body>
    <div id="canvas_container"></div>
</body>
</html>


in IE only LMB(0) is detected, in Chrome left(0) and middle(1) and default context menu is displayed, when I disable it inside body tag (as commented-out) context menu is not displayed at all, but I still cannot get the alert with RMB(2),

thank you for all the hints/support, Borys

like image 508
Borys Avatar asked Jul 07 '11 04:07

Borys


1 Answers

Looks like SVG elements do not fire the "click" event instead they fire "contextmenu" on right click. I am using d3.js to bind the events, so this worked for me:

.on("contextmenu", function(data, index) {
     //handle right click

     //stop showing browser menu
     d3.event.preventDefault();
});
like image 162
Phil McCullick Avatar answered Sep 17 '22 12:09

Phil McCullick