Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save quezo/6275018 to your computer and use it in GitHub Desktop.
Save quezo/6275018 to your computer and use it in GitHub Desktop.
A CodePen by Alex Vazquez.
<h1>JQuery Handle Single & Double Clicks on Same Element</h1>
<br />
<h1 id="clickme">CLICK ME ONCE OR TWICE</h1>
<h1 id="result">Result of Click</h1>

Jquery Extension to Handle Clicks and Double Clicks

This Jquery extension allows you to handle single and double clicks on the same element correctly.

A CodePen by Alex Vazquez.

$.fn.singleAndDouble = function(singleClickFunc, doubleClickFunc) {
// This means it'll take a minimum of 200ms to take the single
// click action. If it's too short the single and double actions
// will be called.
// The default time between clicks on windows is 500ms (http://en.wikipedia.org/wiki/Double-click)
// Adjust accordingly.
var timeOut = 200;
var timeoutID = 0;
var ignoreSingleClicks = false;
this.on('click', function(event) {
if (!ignoreSingleClicks) {
// The double click generates two single click events
// and then a double click event so we always clear
// the last timeoutID
clearTimeout(timeoutID);
timeoutID = setTimeout(function() {
singleClickFunc(event);
}, timeOut);
}
});
this.on('dblclick', function(event) {
clearTimeout(timeoutID);
ignoreSingleClicks = true;
setTimeout(function() {
ignoreSingleClicks = false;
}, timeOut);
doubleClickFunc(event);
});
};
var singleClickCalled = false;
$('#clickme').singleAndDouble(
function(event) {
singleClickCalled = true;
$('#result').html('Single Click Captured');
setTimeout(function() {
singleClickCalled = false;
}, 300);
},
function(event) {
if (singleClickCalled) {
// This is actually an error state
// it should never happen. The timeout would need
// to be adjusted because it may be too close
$('#result').html('Single & Double Click Captured');
}
else {
$('#result').html('Double Click Captured');
}
singleClickCalled = false;
}
);
@import url(http://fonts.googleapis.com/css?family=Bevan);
body {
font-family: 'Bevan', cursive;
background-color: #eddfed;
margin: 50px;
}
h1 {
padding: 25px;
background-color: #d7dadb;
text-align: center;
border: 1px solid grey;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment