kores59
kores59

Reputation: 443

JQuery - mousedown,mouseup and click on same element

I have a carousel and I need to make him work as Instagram carousel does. On click change slide, but on mousedown just stop animation. My JQuery :

 $(".fancy-carousel").on('mousedown',function (e) {
    ...stop animation
});

$(".fancy-carousel").on('mouseup',function (e) {
  ..continue animation
});

$(".fancy-carousel").on('click',function (e) {
   ..change slide
});

But i don´t know how can i let script know about difference between "click" and "mousedown". When i click on element and hold for a time, it stop animation but after "mouseup" it trigger "click" event too. Is there any way how to split this events? Or should i do it with some calculating of mouse hold time?

Upvotes: 0

Views: 1816

Answers (1)

Someone
Someone

Reputation: 3568

A “click” is just a full cycle of a “mousedown” and a “mouseup”. You can’t have one without the other.

For your code to know the difference, you’ll need a variable that tracks your intentions.

  1. Create a variable to track your intention - default it to “click”.
var intention = "click";
  1. In your mousedown function, pause the animation and start a timer. We will use this timer to detect how long the mouse is down for (I.e, if it’s for over a second, it’s not a click and you just want to trigger mouseup)
var detectIntention = setTimeout(function(){
    intention = "mouseup";
})
  1. In your mouse up function, cancel this timeout. If mouse up is called after just a few MS, then you want to do a click.
clearTimeout(detectIntention);

if (intention === "mouseup") {
  // do mouseup stuff
}
// reset intention
intention = click;
  1. Check in your click function that you wanted to do a click;
if (intention === "click") {
  // do click stuff
}

Upvotes: 2

Related Questions