A
A
Andrey Frolov2015-11-01 10:28:09
JavaScript
Andrey Frolov, 2015-11-01 10:28:09

How can I make it work when I click on the mouse wheel?

How to make it so that when clicking on an element, element.onclickthe click would work not only on pressing the left mouse button, but also when clicking on the wheel.
Otherwise, if there is a scroll bar in the browser window, then clicking the wheel on the element does not give the desired effect. If there is no scrollbar, then everything is ok.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
M
Markus Kelvin, 2015-11-01
@mmxdesign

The click of the wheel can be tracked by MouseEvent.which
and this value for the wheel is 2.
For example:

$("#text").on('click', function(e) { 
    // данное событие будет выполняться при клике на левую кнопку или на клик колесика
   if( e.which == 1 || e.which == 2 ) {
     // какое нибудь действие 
   }
});

A
amatory10, 2015-11-01
@amatory10

without jQuery:

(function() {
  document.getElementById('text').addEventListener('mousedown', addClickListener);
  function addClickListener(event) {
    if(event.button == 2) return;
    event.preventDefault();
    alert(event.button);
  }
})()

R
Rafael™, 2015-11-01
@maxminimus

What if my iPad doesn't have a wheel?

V
Vitaly Inchin ☢, 2015-11-01
@In4in

Doesn't have the desired effect because you're not overriding the browser's default action.

Element.onclick = function(e){
   if("which" in e ? e.which & 2 : e.button & 4){
       e.preventDefault();
       alert("Нажата средняя клавиша мыши.");
   }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question