How to do mouse hold event in Javascript | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How to do mouse hold event in Javascript

I made an if statement testing if mousepressed is true, else mouseup is true. It won't work at all LINE 136 https://code.sololearn.com/Wvziw6SdnW5t/?ref=app

11th May 2021, 7:22 PM
Clueless Coder
Clueless Coder - avatar
4 Answers
+ 1
you cannot addEventListener to many events at once ^^ you rather should add one by one: btnL.addEventListener("mousedown",mLeft,false) btnL.addEventListener("mouseup",rLeft,false) btnR.addEventListener("mousedown",mRight,false) btnR.addEventListener("mouseup",rRight,false) however, this should work as expected with mouse devices, but could be problematic with touch devices (for wich you should use touch events rather than mouse events). anyway, I had not tested it with mouse device, and with touch device it seems only to work with single short click, not by pressing and holding (add some console.log in each targeted functions to convince yourself when they are called), but in all case, that doesn't produce any effect... I don't have spend time to study your code deeper ;P
11th May 2021, 8:52 PM
visph
visph - avatar
+ 1
Is p.left and p.right working as expected? The p.left will be false every time the rRight() function is invoked because of line 174. Even when line 162 isPressedLeft is true and mLeft() is called where p.left is set to true, at line 174 !isPressedRight is also true and as I said before rRight() is called and p.left is set to false. One solution https://code.sololearn.com/WA24A21A8A10
12th May 2021, 9:24 AM
ODLNT
ODLNT - avatar
+ 1
ODLNT Thanks for bringing that to my attention. I think I fixed it
12th May 2021, 2:10 PM
Clueless Coder
Clueless Coder - avatar
0
Mirielle thanks! I do have a slight bug though, it only works for 1 button (right). If I remove the btnR if statement, the left button works, but if I re-add the if statement the right one won't work I set them to individual variables (isPressedLeft and isPressedRight) and I made a debug element. Everything seems to be working fine in terms of the correct booleans. I'm not too sure what's causing 1 button to stop working.
12th May 2021, 6:12 AM
Clueless Coder
Clueless Coder - avatar