How to distinguish between left and right mouse click with jQuery

后端 未结 17 3011
独厮守ぢ
独厮守ぢ 2020-11-21 22:36

How do you obtain the clicked mouse button using jQuery?

$(\'div\').bind(\'click\', function(){
    alert(\'clicked\');
});

this is trigger

17条回答
  •  庸人自扰
    2020-11-21 22:44

    Edit: I changed it to work for dynamically added elements using .on() in jQuery 1.7 or above:

    $(document).on("contextmenu", ".element", function(e){
       alert('Context Menu event has fired!');
       return false;
    });
    

    Demo: jsfiddle.net/Kn9s7/5

    [Start of original post] This is what worked for me:

    $('.element').bind("contextmenu",function(e){
       alert('Context Menu event has fired!');
       return false;
    }); 
    

    In case you are into multiple solutions ^^

    Edit: Tim Down brings up a good point that it's not always going to be a right-click that fires the contextmenu event, but also when the context menu key is pressed (which is arguably a replacement for a right-click)

提交回复
热议问题