4

How do I cancel single click event when double click event fires?

I have already looked at some related and I found something that works

Need to cancel click/mouseup events when double-click event detected

function singleClick(e) {
    // do something, "this" will be the DOM element
}

function doubleClick(e) {
    // do something, "this" will be the DOM element
}

$(selector).click(function(e) {
    var that = this;
    setTimeout(function() {
        var dblclick = parseInt($(that).data('double'), 10);
        if (dblclick > 0) {
            $(that).data('double', dblclick-1);
        } else {
            singleClick.call(that, e);
        }
    }, 300);
}).dblclick(function(e) {
    $(this).data('double', 2);
    doubleClick.call(this, e);
});

However, if I use .on("click") instead of .click(), this code doesn't work.

Any idea why this is? I have to use .on() so using .click() is not an option

Community
  • 1
  • 1
developarvin
  • 4,940
  • 12
  • 54
  • 100
  • `.click` calls `.on` internally, so it should work either way. How are you calling it? If have to use event delegation, things might be a bit different. – Felix Kling Jul 09 '12 at 08:29
  • [Clicks have already happened](http://www.w3.org/TR/DOM-Level-3-Events/#events-mouseevent-event-order) if you got to double click so at face value *How do I cancel single click event when double click event fires?* doesn't work. – Esailija Jul 09 '12 at 08:32
  • @Esailija so that means that I can't cancel, but I can chose to ignore it then? – developarvin Jul 09 '12 at 08:46
  • @arvinsim I'm not sure how you would that since if your `"dblclick"` handler fires, the clicks have already fired. Any timeout hacks don't work too robustly either because you cannot know what timer value the OS is using for double clicks. I suggest an alternative UI design that doesn't rely on this "paradox" :D – Esailija Jul 09 '12 at 08:52

1 Answers1

1

If you do .on('click') you need to do .on('dblclick'). (had the same issue where the dbl did not fire)

Also, if the event is not firing, it may be because you added selector after this function did it's thing.

so...

...instead of $(selector).on('click', function(){}) ...do $(selectors parent).on('click', selector, function(){}).

it's the super neat upgrade to .live()

function singleClick(e) {
    // do something, "this" will be the DOM element
}

function doubleClick(e) {
    // do something, "this" will be the DOM element
}

$('selector-parent').on('click', 'selector', function(e) {
    var that = this;
    setTimeout(function() {
        var dblclick = parseInt($(that).data('double'), 10);
        if (dblclick > 0) {
            $(that).data('double', dblclick-1);
        } else {
            singleClick.call(that, e);
        }
    }, 300);
}).on('dblclick', 'selector', function(e) {
    $(this).data('double', 2);


doubleClick.call(this, e);
});
AWM
  • 11
  • 1