Saturday, May 15, 2021

Handling both single click and double click in JavaScript

Live code: https://jsfiddle.net/91zoa2qj/1/

HTML and CSS:
<div id="something">Click or double click me</div>
<hr/>
<div id="good">Click or double click me</div>


<style>
#something, #good {
  background-color: lemonchiffon;
}
</style>

JS:
addGlobalEventListener(
    'click',
    '#something',
    debounceSingleClickOnly(sayHello)
);

addGlobalEventListener(
    'dblclick',
    '#something',
    sayWorld
);

addGlobalEventListener(
    'click',
    '#good',
    debounceSingleClickOnly(sayHello)
);

addGlobalEventListener(
    'dblclick',
    '#good',
    sayWorld
);


    
let counter = 0;
function sayHello({target: {id}}) {
    ++counter;
	console.log(`${counter}. clicked ${id}`);
}


function sayWorld({target: {id}}) {
    ++counter;
	console.log(`${counter}. double-clicked ${id}`);
}


function addGlobalEventListener(type, selector, callback) {
    document.addEventListener(type, (e) => {
        if (e.target.matches(selector)) {
            callback(e);
        }
    });
}


function debounce(func, wait, immediate) {
    let timeout;
    return function () {
        const context = this,
            args = arguments;
        const later = function () {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        const callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
}

function debounceSingleClickOnly(func, timeout = 500) {
    function eventHandler(event) {
        const { detail } = event;
        if (detail > 1) {
            return;
        }

        func.apply(this, arguments);
    }

    return debounce(eventHandler, timeout);
}

No comments:

Post a Comment