What is a browser-based way to capture all clicks with the click of a button?

What is the best way to execute a function exactly once every time a button is pressed, regardless of speed and browser?

Simply linking the click handler works fine in all browsers except IE.

In IE, when a user clicks too fast, only "dblclick" fires, so the "click" handler never executes. Other browsers fire both events, so this is not a problem for them.

The obvious solution / hack (at least for me) is to hook up the dblclick handler in IE, which launches my click handler twice. Another idea is to track clicks on your own using mousedown / mouseup, which seems pretty primitive and probably relates to the framework, and not to my application.

So what is the best / usual / right way to handle this? (pure javascript or jquery is preferred)

+3
source share
2 answers

, jQuery :

function eventHandler(event) {
    // your handler code here
    doSomeMagic();
}

var element = $('#element');

element.one('click.someNameSpace', function(event){
    // first we unbind all other event handlers with this namespace
    element.unbind('.someNameSpace');

    // then we execute our eventHandler
    eventHandler();
}).one('dblclick.someNameSpace',  function(event){
    // If this fires first, we also unbind all event handlers
    element.unbind('.someNameSpace');

    // and then execute our eventHandler
    eventHandler();
});

, , , , .

+1

Mousedown mouseup , , , , , IE - , mousedown mouseup. dblclick , , .

<div onclick="clk()" ondblclick="clk()"></div>

lastclicktime=0
function clk(){
    var time=new Date().getTime()
    if(time>lastclicktime+50){
        lastclicktime=time
        //Handle click
    }
}

, , , , , Firefox dblclick , Date.

+1

Source: https://habr.com/ru/post/1739816/


All Articles