Why is the mousedown event being fired after click instead of during?

394 Views Asked by At

I have a div class "guessed" and have a timer to detect whether a short press and long press. When testing, the console logs "MOUSEDOWN" after the press instead of on the press.

The console also logs "SHORT PRESS" even if it's held for longer than 2 seconds.

I've tested the code on JSFiddle and it's working fine. However within my website, the code doesn't work. Can anyone spot the error? Many thanks

var timer = 0;
var timerInterval;

$(document).on('mousedown', '.guessed', function() {
  console.log("MOUSEDOWN");
  timerInterval = setInterval(function() {
    timer += 1;
  }, 300);
});

$(document).on('mouseup', '.guessed', function() {
  if (timer < 1) {
    console.log("SHORT PRESS");
    clearInterval(timerInterval);
    timer = 0;
    return;
  }

  console.log("LONG PRESS");
  clearInterval(timerInterval);
  timer = 0;
});
.guessed { border:1px solid red; width:100px; height:100px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='guessed'>mouse me</div>

1

There are 1 best solutions below

0
HAMZA HUMMAM On

You can simply use html attributes for mouseup and mousedown events and call custom defined JavaScript functions just like in the following example :

var timer = 0,timerInterval;

function mousedownfunction() {
    console.log("MOUSE DOWN");
    timerInterval = setInterval(function() {
        timer += 1;
    }, 300);
}

function mouseupfunction() {
    console.log("MOUSE UP");
 
    if (timer < 1) {
        console.log("SHORT PRESS");

        clearInterval(timerInterval);
        timer = 0;
        return;
    } else {
        console.log("LONG PRESS");
        clearInterval(timerInterval);
        timer = 0;
        return;
    }
}
<div class="guessed" onmousedown="mousedownfunction()" onmouseup="mouseupfunction()">
    <p>Mouse</p>
</div>