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>
You can simply use html attributes for
mouseupandmousedownevents and call custom defined JavaScript functions just like in the following example :