JavaScript - event.which always return 1 for hovering

781 views Asked by At

I would like to hover & mouse left click at the same time on a <div> but event.which always returns 1 :

$('#element2').mouseenter(function(event) {
    switch (event.which) {
        case 1:  alert('Left Mouse pressed.');   break;
        case 2:  alert('Middle Mouse pressed.'); break;
        case 3:  alert('Right Mouse pressed.');  break;
        default: alert('You have a strange Mouse!');
    }
});

Complete example here on jsfiddle.

A mousedown works but hover & mouseover & mouseenter always return 1.

Well if I replace event.which by event.buttons it returns the good result on Firefox but I red that event.buttons is not compatible with other browsers.

=> Is it a bug ? Do you have any browser compatible alternative solutions for my problem ? Thanks

1

There are 1 answers

1
A. Wolff On BEST ANSWER

If you want to handle it for all browsers (even i'm unable to replicate issue on chrome), you can use a global flag and check for it instead:

$(document).on('mousedown', function(e){
    window.btnClicked = e.which;
}).on('mouseup', function(){
    window.btnClicked = undefined;
});

$('#element2').mouseenter(function(event) {
    switch (window.btnClicked) {
        case 1:  alert('Left Mouse pressed.');   break;
        case 2:  alert('Middle Mouse pressed.'); break;
        case 3:  alert('Right Mouse pressed.');  break;
        default: alert('You have a strange Mouse!');
    }
});