Bind Different Events to Click and Double Click

You might want a link to have a special action when double-clicked which prevents the default action of the link (go to another page). So:

Double-click: does something special, does not do normal click event at all
Click: works as normal

You'll need to have a very slight delay on firing off the normal click action, which you cancel when the double click event happens.

function doClickAction() {
  $("#click h2").append("•"); 
}
function doDoubleClickAction() {
  $("#double-click h2").append("•"); 
}

var timer = 0;
var delay = 200;
var prevent = false;

$("#target")
  .on("click", function() {
    timer = setTimeout(function() {
      if (!prevent) {
        doClickAction();
      }
      prevent = false;
    }, delay);
  })
  .on("dblclick", function() {
    clearTimeout(timer);
    prevent = true;
    doDoubleClickAction();
  });
Check out this Pen!

Comments

  1. User Avatar
    James
    Permalink to comment#

    Try click, click then double click, your script fail

  2. User Avatar
    Radek Surani
    Permalink to comment#

    Thanks, it’s very helpful to me.

  3. User Avatar
    BugFinder
    Permalink to comment#

    in the moment the double click selects the text automaticly a normal click is assigned?

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-anchoricon-closeicon-emailicon-linkicon-logo-staricon-menuicon-nav-guideicon-searchicon-staricon-tag