Home

JavaScript Press And Hold Button

Blog Date 22 November 2021

The Code

<input type="button" value="<<" onmousedown="MyMouseDown()" onmouseup="MyMouseUp()" />

           <script>

                var MyPosition = 0;
                var MyTimer;

                function MyMouseDown(){
                    MyTimer = setInterval(function () {
                        MyPosition += 1;
                        console.log(MyPosition);
                    }, 50)
                }

                function MyMouseUp() {
                    clearTimeout(MyTimer);
                }

            </script>

The Explanation

If you call a function in JavaScript by pressing a button, that function is called - as you'd expect. But there are times where you want to "keep the button pressed". For example in a game the left button has been pressed to move a character left. But for each move rather than having to constantly re=press the button it makes sense to keep the button pressed.

JS can't... really... quite do this. So all we are doing here is saying - ahem - "on mouse down - run this code". The thing is when that code is run it starts a setTimout loop running. This setTimeout loop keeps on running until onmouseup function MyMouseUp() is called. This clears the setTimeout.

It's worth noting that BEFORE the functions we declare a var MyTimer. This becomes the setTimeout when the button is pressed with the mouse and is then cleared onmouseup.


contact Ren via [email protected]

Reader's Comments

Post Your Comment Posts/Links Rules

Name

Comment

Add a RELEVANT link (not required)

Upload an image (not required)

No uploaded image
Real person number
Please enter the above number below




Home
Admin Ren's Biking Blog