0

When click event is fired with "right button" it is not caught by "else if" in in the "select" function. Most annoying thing is that it is caught in any other sample pages that I made earlier. Please help me in debugging this problem.

document.addEventListener('click' ,this.select.bind(this) ,false);

Filesystem.prototype.select = function(event){
    if(event.button === 0){
         // Code that's working fine
    }
    else if(event.button === 2){
        alert("hello");
    }
}
Chris Martin
  • 30,334
  • 10
  • 78
  • 137

1 Answers1

0

The basic problem is that you cannot intercept right click using click event. Instead, use mousedown or contextmenu.

See this JSFiddle: https://jsfiddle.net/0rd5dc3v/5/.

var select = function(event){
    console.log(event);
    if(event.button === 0){
         // Code that's working fine
    }
    else if(event.button === 2){
        alert("hello");
    }
}

document.getElementsByClassName('click')[0].addEventListener('click' ,select,false);

document.getElementsByClassName('mousedown')[0].addEventListener('mousedown' ,select,false);

Right click is not captured for the red square (listening for click events) but is captured for the blue square (listening for mousedown events).

Matthew King
  • 1,342
  • 7
  • 13
  • When you click an element on an HTML element the object that is passed to the event handler has an attribute called 'button' which stores the integer code for the mouse button that was pressed when the event was fired. So you can catch right click with 'click' event – user3809584 Jul 06 '15 at 11:04