1

I want to detect if a user right-clicks a row in a table (datatables powered).

Now, the following code works fine if I use a non-ajax source:

oTable.$('tr').mousedown(function(e) {
    if (e.which === 3) { //Right Mousebutton was clicked
        window.sData = oTable.fnGetData( this );
        jQuery(this).contextMenu({ x: e.pageX + 10, y: e.pageY + 10});
    }
});

However, it doesn't work if I use an ajax source, so I looked around and tried:

jQuery('#myTable tbody').on( 'click', 'tr', function (e) {
    alert("a click!");
    if (e.which === 3) { //Right Mousebutton was clicked
        alert("actually it was a right click!");
    }
});

This code does detect regular clicks, but if fails to recognize a right click.

What am I doing wrong?

madth3
  • 7,275
  • 12
  • 50
  • 74
mattosmat
  • 610
  • 1
  • 11
  • 27

2 Answers2

3

Something like this?

jQuery('#myTable tbody').mousedown(function(e){ 
    if( e.button == 2 ) { 
      alert('Right mouse button!'); 
      return false; 
    } 
    return true; 
  }); 
Oleksii Aza
  • 5,368
  • 28
  • 35
  • Thank you for your help. It helped me figure out what I had to change -although it is not quite right- and I'm upvoting your answer because of that. – mattosmat Jul 11 '13 at 19:44
3

Alexey's code works when you first load the table, but it stops working when you perform some ajax action on it. So the .on(...) method has to be used instead.

The code I'm currently using looks like this:

jQuery('#myTable tbody').on( 'mousedown', 'tr', function (e) {
     alert("mouse event detected!"); 
     if( e.button == 2 ) { 
        alert('Right mouse button!'); 
        return false; 
     } 
     return true; 
}); 
mattosmat
  • 610
  • 1
  • 11
  • 27