QuantumHive
QuantumHive

Reputation: 5683

jQuery: simulate onClick with a specific mouse BUTTON

So when using

$("#myElement").click(function(){
    //do something
});

the jQuery API notes:

The click event is only triggered after this exact series of events:

  • The mouse button is depressed while the pointer is inside the element.
  • The mouse button is released while the pointer is inside the element.

This works for BOTH left and right mousebutton clicks.

Now I want to simulate this with only one specific mouse button (doesn't matter which one, it's just the concept to simulate click()). I know you can use:

$("#myElement").mousedown(function(event){
    if(event.button == 0) //leftclick
    else if (event.button == 1) //middleclick
    else if (event.button == 2) //rightclick
}

This is all great and well, but note this wouldn't be the same as click(). Again from the jQuery API:

If the user clicks on an element, drags away from it, and releases the button, this is still counted as a mousedown event. This sequence of actions is treated as a "canceling" of the button press in most user interfaces, so it is usually better to use the click event unless we know that the mousedown event is preferable for a particular situation.

Analogous for mouseup(). So using one of both is obviously and definitely not the desired result. So how can we achieve the desired result?

Upvotes: 0

Views: 656

Answers (1)

PlantTheIdea
PlantTheIdea

Reputation: 16369

Based on your explanation, you have answered your question in the question itself. You cannot simulate (or in jQuery terms, .trigger()) a click as a single button. however you can perform the e.which detection you were doing for mousedown on click and it will do exactly what you want.

$("#myElement").click(function(e){
    switch(e.which){
        case 1:
            // do left click stuffs
            break;
        case 2:
            // do middle click stuffs
            break;
        case 3:
            // do right click stuffs
            break;
    }
});

Or if you only wanted to do an action only when a specific button is clicked and do nothing otherwise:

$("#myElement").click(function(e){
    if(e.which === 1){
        // do your stuffs
    }
});

Then if you want to simulate it with a different event, just make the action a function:

function leftClick($el,e){
    if(e.which === 1){
        // do your magic with $el
    }
}

Then you can call it with anything you want

$("#myElement").click(function(e){
    leftClick($(this),e);
});

$('.SomethingElse').on('click',function(e){
    leftClick($('#myElement'),e);
});

to answer the obvious "why not test the e.which before passing to the function? The answer is ... personal coding choice. The way I did it is less verbose and if you call it 30,000 times it will be faster ... but to each their own, either way will work.

Upvotes: 1

Related Questions