0

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?

Object object
  • 872
  • 6
  • 18
kores59
  • 443
  • 1
  • 5
  • 16

1 Answers1

2

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
}
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Lewis
  • 3,479
  • 25
  • 40
  • This works awesome. But one more thing, is possible to make this way on mobile? I tried just change "mousedown" with "keydown","taphold","keypress", but not even one of this events works. It always just skip to "click" and show standard browser options like copy, download image and others.. – kores59 Jun 11 '19 at 08:57
  • @kores59 Try using `touchstart` and `touchend` - taken from [here](https://stackoverflow.com/questions/6139225/how-to-detect-a-long-touch-pressure-with-javascript-for-android-and-iphone). – Lewis Jun 11 '19 at 08:59