Right mouse click detection on SVG shape in JavaScript not working
Asked Answered
C

3

14


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

Callisthenics answered 7/7, 2011 at 4:55 Comment(0)
P
30

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();
});
Performative answered 21/10, 2011 at 20:48 Comment(1)
In Chrome this is still true as of today, version 29.0.1547. bizarre!Redstone
M
2

Posting the link to a good solution for d3 contextmenu here.

Github link : https://github.com/patorjk/d3-context-menu

Plunker : http://plnkr.co/edit/hAx36JQhb0RsvVn7TomS?p=preview ``

Maceio answered 13/10, 2015 at 9:56 Comment(0)
E
0

The following jQuery context menu plugin works with D3 and SVG: https://github.com/arnklint/jquery-contextMenu

Equipollent answered 29/1, 2013 at 18:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.