简体   繁体   中英

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

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 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM