Double click ambiguity in Jquery?

妖精的绣舞 提交于 2019-12-04 12:45:52

The way around the problem is to use a timeout for the click event to give the user time to doubleclick.
If the user clicks twice within a certain timeframe, it's a doubleclick, if the user only clicks once, it's a normal click:

$('#press').click(function (event) {
    event.preventDefault();

    if ( $(this).data('dblclicked') ) {
        $('#log').text('No google today!');
        clearTimeout( $(this).data('clicked') );
        $(this).data('dblclicked', false);
    }else{
        var self = this;
        $(this).data('dblclicked', true).data('clicked', setTimeout(function() {
            $('#log').text('google !');
            $(self).data('dblclicked', false);
        },300));
    }
});

FIDDLE

I got the closest solution by ,

<a id="press" href="javascript:void(0)" onclick="singleClick(event)"
    ondblclick="doubleClick(event)">Click here</a>

<div id="log"></div>

My JavaScript will be ,

var timer;
var status = 1;

function singleClick(event) {

    event.preventDefault();
    status = 1;
    timer = setTimeout(function() {
        if (status == 1) {
            alert("I am single click !");
            document.getElementById("log").innerHTML ='I  am single click !';
        }
    }, 500);

}

function doubleClick(event) {

    event.preventDefault();
    clearTimeout(timer);
    status = 0;
    alert("I am double click !");
    document.getElementById("log").innerHTML = 'I  am a double  click!';
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!