Programing

싱글 클릭 이벤트와 더블 클릭 이벤트를 어떻게 구분하나요?

crosscheck 2020. 8. 19. 07:37
반응형

싱글 클릭 이벤트와 더블 클릭 이벤트를 어떻게 구분하나요?


나는 id와 함께 단일 버튼을 가지고 있습니다 "my_id". 이 요소로 두 개의 jQuery 이벤트를 첨부했습니다.

1.

$("#my_id").click(function() { 
    alert('single click');
});

2.

$("#my_id").dblclick(function() {
    alert('double click');
});

그러나 매번 그것은 나에게 single click


첫 번째 클릭 후 다른 클릭이 있는지 확인하려면 시간 제한을 사용해야합니다.

트릭은 다음과 같습니다 .

// Author:  Jacek Becela
// Source:  http://gist.github.com/399624
// License: MIT

jQuery.fn.single_double_click = function(single_click_callback, double_click_callback, timeout) {
  return this.each(function(){
    var clicks = 0, self = this;
    jQuery(this).click(function(event){
      clicks++;
      if (clicks == 1) {
        setTimeout(function(){
          if(clicks == 1) {
            single_click_callback.call(self, event);
          } else {
            double_click_callback.call(self, event);
          }
          clicks = 0;
        }, timeout || 300);
      }
    });
  });
}

용법:

$("button").single_double_click(function () {
  alert("Try double-clicking me!")
}, function () {
  alert("Double click detected, I'm hiding")
  $(this).hide()
})
<button>Click Me!</button>

편집하다:

아래에 설명 된대로 기본 dblclick이벤트 사용을 선호합니다 . http://www.quirksmode.org/dom/events/click.html

또는 jQuery에서 제공하는 것 : http://api.jquery.com/dblclick/


dblclick이벤트 의 동작은 Quirksmode 에서 설명 합니다.

의 이벤트 순서 dblclick는 다음과 같습니다.

  1. mousedown
  2. mouseup
  3. 딸깍 하는 소리
  4. mousedown
  5. mouseup
  6. 딸깍 하는 소리
  7. dblclick

이 규칙에 대한 한 가지 예외는 (물론) 사용자 지정 순서가 다음과 같은 Internet Explorer입니다.

  1. mousedown
  2. mouseup
  3. 딸깍 하는 소리
  4. mouseup
  5. dblclick

보시다시피 동일한 요소에서 두 이벤트를 함께 수신하면 click핸들러 에 대한 추가 호출이 발생 합니다.


간단한 기능. jquery 또는 기타 프레임 워크가 필요하지 않습니다. 함수를 매개 변수로 전달

<div onclick="doubleclick(this, function(){alert('single')}, function(){alert('double')})">click me</div>
    <script>
        function doubleclick(el, onsingle, ondouble) {
            if (el.getAttribute("data-dblclick") == null) {
                el.setAttribute("data-dblclick", 1);
                setTimeout(function () {
                    if (el.getAttribute("data-dblclick") == 1) {
                        onsingle();
                    }
                    el.removeAttribute("data-dblclick");
                }, 300);
            } else {
                el.removeAttribute("data-dblclick");
                ondouble();
            }
        }
    </script>

동작이 브라우저에 따라 다릅니다.

동일한 요소에 대해 click 및 dblclick 이벤트 모두에 핸들러를 바인딩하는 것은 바람직하지 않습니다. 트리거되는 이벤트의 순서는 브라우저마다 다르며, 일부는 dblclick 전에 두 번의 클릭 이벤트를 수신하고 다른 일부는 하나만 수신합니다. 더블 클릭 민감도 (더블 클릭으로 감지되는 클릭 사이의 최대 시간)는 운영 체제와 브라우저에 따라 다를 수 있으며 사용자가 구성 할 수있는 경우가 많습니다.

http://api.jquery.com/dblclick/

Firefox에서 코드를 실행하면 click()핸들러 의 alert () 가 두 번째 클릭을 방지합니다. 이러한 경고를 제거하면 두 이벤트가 모두 표시됩니다.


더블 클릭 (두 번 클릭)하려면 먼저 한 번 클릭해야합니다. click()경고가 팝업 때문에 핸들러 화재는 첫 번째 클릭에, 그리고, 당신은 해고 할 수있는 두 번째 클릭 할 수있는 기회가없는 dblclick()핸들러를.

처리기를 변경하여 an 이외의 작업을 수행 alert()하면 동작을 볼 수 있습니다. (아마도 요소의 배경색을 변경) :

$("#my_id").click(function() { 
    $(this).css('backgroundColor', 'red')
});

$("#my_id").dblclick(function() {
    $(this).css('backgroundColor', 'green')
});

더 많은 임시 상태와 setTimeout을 사용하는 대신 객체 detail에서 액세스 할 수있는 라는 네이티브 속성 이 있습니다 event!

element.onclick = event => {
   if (event.detail === 1) {
     // it was a single click
   } else if (event.detail === 2) {
     // it was a double click
   }
};

최신 브라우저와 IE-9도 지원합니다. :)

출처 : https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail


이 답변 중 어느 것도 내 요구를 충족시키지 않았으므로 @AdrienSchuler가 게시 한 요점에서 영감을 얻은 솔루션을 만들었습니다. 한 번의 클릭과 두 번의 클릭을 요소에 바인딩하려는 경우에만이 솔루션을 사용하십시오. 그렇지 않으면 네이티브 clickdblclick리스너를 사용하는 것이 좋습니다 .

차이점은 다음과 같습니다.

  • Vanillajs, 종속성 없음
  • setTimeout에서 클릭 또는 더블 클릭 처리기를 처리 할 때까지 기다리지 마십시오.
  • 두 번 클릭하면 먼저 클릭 핸들러가 실행 된 다음 doubleclick 핸들러가 실행됩니다.

자바 스크립트 :

function makeDoubleClick(doubleClickCallback, singleClickCallback) {
    var clicks = 0, timeout;
    return function() {
        clicks++;
        if (clicks == 1) {
            singleClickCallback && singleClickCallback.apply(this, arguments);
            timeout = setTimeout(function() { clicks = 0; }, 400);
        } else {
            timeout && clearTimeout(timeout);
            doubleClickCallback && doubleClickCallback.apply(this, arguments);
            clicks = 0;
        }
    };
}

용법:

var singleClick = function(){ console.log('single click') };
var doubleClick = function(){ console.log('double click') };
element.addEventListener('click', makeDoubleClick(doubleClick, singleClick));

아래는 jsfiddle에서의 사용법이며 jQuery 버튼은 허용되는 답변의 동작입니다.

jsfiddle


에 기초하여 또 다른 간단한 바닐라 솔루션 A1rPun의 대답은 (참조 그의 바이올린 JQuery와 솔루션을, 둘 다에있는 이 하나 ).

사용자가 두 번 클릭 할 때 단일 클릭 핸들러를 트리거하지 않는 것 같습니다. 단일 클릭 핸들러는 지연 후에 반드시 트리거됩니다.

var single = function(e){console.log('single')},
    double = function(e){console.log('double')};

var makeDoubleClick = function(e) {

  var clicks = 0,
      timeout;

  return function (e) {

    clicks++;

    if (clicks == 1) {
      timeout = setTimeout(function () {
        single(e);
        clicks = 0;
      }, 250);
    } else {
      clearTimeout(timeout);
      double(e);
      clicks = 0;
    }
  };
}
document.getElementById('btnVanilla').addEventListener('click', makeDoubleClick(), false);

우수한 jQuery Sparkle 플러그인을 사용하십시오. 플러그인은 첫 번째와 마지막 클릭을 감지하는 옵션을 제공합니다. 다른 클릭에 이어 첫 번째 클릭이되었는지 감지하여 클릭과 dblclick을 구별하는 데 사용할 수 있습니다.

http://balupton.com/sandbox/jquery-sparkle/demo/ 에서 확인하십시오.


다음은 임의의 이벤트 수에 대한 jeum 코드의 대안입니다.

 var multiClickHandler = function (handlers, delay) {
    var clicks = 0, timeout, delay = delay || 250;
    return function (e) {
      clicks++;
      clearTimeout(timeout);
      timeout = setTimeout(function () {
        if(handlers[clicks]) handlers[clicks](e);
        clicks = 0;
      }, delay);
    };
  }

  cy.on('click', 'node', multiClickHandler({
    1: function(e){console.log('single clicked ', e.cyTarget.id())},
    2: function(e){console.log('double clicked ', e.cyTarget.id())},
    3: function(e){console.log('triple clicked ', e.cyTarget.id())},
    4: function(e){console.log('quadro clicked ', e.cyTarget.id())},
    // ...
  }, 300));

cytoscape.js 앱에 필요했습니다 .


I wrote a simple jQuery plugin that lets you use a custom 'singleclick' event to differentiate a single-click from a double-click:

https://github.com/omriyariv/jquery-singleclick

$('#someDiv').on('singleclick', function(e) {
    // The event will be fired with a small delay.
    console.log('This is certainly a single-click');
}

How to differentiate between single clicks and double clicks on one and the same element?

If you don't need to mix them, you can rely on click and dblclick and each will do the job just fine.

A problem arises when trying to mix them: a dblclick event will actually trigger a click event as well, so you need to determine whether a single click is a "stand-alone" single click, or part of a double click.

In addition: you shouldn't use both click and dblclick on one and the same element:

It is inadvisable to bind handlers to both the click and dblclick events for the same element. The sequence of events triggered varies from browser to browser, with some receiving two click events before the dblclick and others only one. Double-click sensitivity (maximum time between clicks that is detected as a double click) can vary by operating system and browser, and is often user-configurable.
Source: https://api.jquery.com/dblclick/

Now on to the good news:

You can use the event's detail property to detect the number of clicks related to the event. This makes double clicks inside of click fairly easy to detect.

The problem remains of detecting single clicks and whether or not they're part of a double click. For that, we're back to using a timer and setTimeout.

Wrapping it all together, with use of a data attribute (to avoid a global variable) and without the need to count clicks ourselves, we get:

HTML:

<div class="clickit" style="font-size: 200%; margin: 2em; padding: 0.25em; background: orange;">Double click me</div>

<div id="log" style="background: #efefef;"></div>

JavaScript:

<script>
var clickTimeoutID;
$( document ).ready(function() {

    $( '.clickit' ).click( function( event ) {

        if ( event.originalEvent.detail === 1 ) {
            $( '#log' ).append( '(Event:) Single click event received.<br>' );

            /** Is this a true single click or it it a single click that's part of a double click?
             * The only way to find out is to wait it for either a specific amount of time or the `dblclick` event.
             **/
            clickTimeoutID = window.setTimeout(
                    function() {
                        $( '#log' ).append( 'USER BEHAVIOR: Single click detected.<br><br>' );
                    },
                    500 // how much time users have to perform the second click in a double click -- see accessibility note below.
                );

        } else if ( event.originalEvent.detail === 2 ) {
            $( '#log' ).append( '(Event:) Double click event received.<br>' );
            $( '#log' ).append( 'USER BEHAVIOR: Double click detected.<br>' );
            window.clearTimeout( clickTimeoutID ); // it's a dblclick, so cancel the single click behavior.
        } // triple, quadruple, etc. clicks are ignored.

    });

});
</script>

Demo:

JSfiddle


Notes about accessibility and double click speeds:

  • As Wikipedia puts it "The maximum delay required for two consecutive clicks to be interpreted as a double-click is not standardized."
  • No way of detecting the system's double-click speed in the browser.
  • Seems the default is 500 ms and the range 100-900mms on Windows (source)
  • Think of people with disabilities who set, in their OS settings, the double click speed to its slowest.
    • If the system double click speed is slower than our default 500 ms above, both the single- and double-click behaviors will be triggered.
    • Either don't use rely on combined single and double click on one and the same item.
    • Or: add a setting in the options to have the ability to increase the value.

It took a while to find a satisfying solution, I hope this helps!


I like to avoid jquery (and other 90-140k libs), and as noted browsers handle onclick first, so here is what I did on a website I created (this example also covers getting a clicked location local x y )

clicksNow-0; //global js, owell

function notify2(e, right) {  // called from onclick= and oncontextmenu= (rc)
var x,y,xx,yy;
var ele = document.getElementById('wrap');  
    // offset fixed parent for local win x y
var xxx= ele.offsetLeft;
var yyy= ele.offsetTop;

//NScape
if (document.layers || document.getElementById&&!document.all) {
    xx= e.pageX;
    yy= e.pageY;
} else {
    xx= e.clientX;
    yy= e.clientY;
}
x=xx-xxx;
y=yy-yyy;

clicksNow++;
    // 200 (2/10ths a sec) is about a low as i seem to be able to go
setTimeout( "processClick( " + right + " , " + x + " , " + y + ")", 200);
}

function processClick(right, x, y) {
if (clicksNow==0) return; // already processed as dblclick
if (clicksNow==2) alert('dbl');
clicksNow=0;
    ... handle, etc ...
}

hope that helps


this worked for me–

var clicked=0;
function chkBtnClcked(evnt) {
    clicked++;
    // wait to see if dblclick
    if (clicked===1) {
        setTimeout(function() {
            clicked=0;
            .
            .
        }, 300); // test for another click within 300ms
    }
    if (clicked===2) {
        stopTimer=setInterval(function() {
            clicked=0;
            .
            .
        }, 30*1000); // refresh every 30 seconds
    }
}

usage–

<div id="cloneimages" style="position: fixed;" onclick="chkBtnClcked(evnt)"  title="Click for next pic; double-click for slide show"></div>

Just posting the native HTML answer just in case the need is to be easy and HTML.

<p ondblclick="myFunction()" id = 'id'>Double-click me</p>

This of course has native Jquery options. ie... $('#id').attr('ondblclick',function(){...}) or, as stated previously, $('#id').dblclick(function(){...});

참고URL : https://stackoverflow.com/questions/5497073/how-to-differentiate-single-click-event-and-double-click-event

반응형