Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listen to rightclick on svg element with Raphael.js

I need to respond when a user right clicks on an element created with Rapahel.js. I read that you should just attach a click event handler and then decide which mouse button the user clicked. I can't get this to work.

<!DOCTYPE html>
<html>
<head>
<script src="http://raphaeljs.com/raphael.js"></script>
<script>
    window.onload = function() {
       var r = Raphael('demo', 640, 480);
       r.rect(10, 10, 400, 400).attr({fill: 'red'}).click(function(){
          alert('test');
       });;
    };
</script>
</head>
<body>
    <div id="demo"></div>
</body>
</html>

The alert box will only show when clicking the left button on the mouse. Any suggestions about how to show the alert box when clicking the right button?

I've seen this little trick with jQuery:

$(r.rect(10, 10, 400, 400).attr({fill: 'red'}).node).bind('contextmenu', function(){
            alert('test');
        });

But also read this comment about it:

Yes, that works too, but only with jQuery, and it's also better not to ever use .node, since Raphael sometimes re-creates nodes - so you lose your event handler.

like image 296
John Avatar asked May 09 '12 09:05

John


1 Answers

You can use mousedown and test for e.which. This works in FF and Chrome:

var r = Raphael('demo', 640, 480);
r.rect(10, 10, 400, 400).attr({fill: 'red'}).mousedown(function(e){
    if (e.which == 3)
        alert("hi")
});

For a cross browser solution you might want to take a look at e.button as well:
http://www.quirksmode.org/js/events_properties.html#button

like image 90
mihai Avatar answered Nov 04 '22 03:11

mihai