Single and double click in JS

Shows how to mix single and double click on a single element. Includes useful notes on the topic.

by Fabien Snauwaert

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

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.
				 **/
				var 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.
					);
				$(this).data( 'clickTimeoutID', clickTimeoutID );

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

		});



		// No point in using this one if we need to handle BOTH single and double clicks on an element.
		// This `dblclick` (native or jquery), alone, is only good for double-click-only elements.
		// $( '.clickit' ).dblclick( function( event ) {
		// 	// console.log( 'Double click' );

		// 	$( '#log' ).append( 'Double click event received<br>' );

		// 	console.log( event.originalEvent.detail );
		// });


	/**

	EXPLANATIONS & ITERATIONS:

	- The double click `dblclick` event would also trigger the single click event twice!
	- Could use `detail` to distinguish whether the `click` is part of a double click or single click:
	  - Looked promising…
	    - Cf. this answer and my comments there: https://stackoverflow.com/questions/880608/prevent-click-event-from-firing-when-dblclick-event-fires#comment95723317_29993141
	  - …but this was not enough! Because the first click in a double click...