May 2012
M T W T F S S
« Feb   Jun »
 123456
78910111213
14151617181920
21222324252627
28293031  

Categories

Meta


« | Main | »

Javascript snack: enable both click and doubleclick events on one element

By Bart | May 10, 2012

HTML defines onClick and onDblClick event handlers on all elements. However, if you want to enable both on the same element, something goes wrong. the onClick event gets fired twice! And that is not what we want, so here’s a little Javascript to fix that:

// use these functions to enable *both* onclick and 
// ondblclick on one element:
// usage: onclick="singleClick(someFunction)" 
//        ondblclick="doubleClick(otherFunction)"

singleClickTimeout = null;
function singleClick(fcn) {
    if (singleClickTimeout == null) {
        singleClickTimeout = setTimeout(function() {
            singleClickTimeout = null;
            fcn();
        }, 500);
    }
}
function doubleClick(fcn) {
    if (singleClickTimeout != null) {
        clearTimeout(singleClickTimeout);
        singleClickTimeout = null;
    }
    fcn();
}

Topics: Geekstuff, Snack | Geen reacties »