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 ren@techsolus.co.uk
Reader's Comments
Name
Comment
Add a RELEVANT link (not required)
Upload an image (not required)
Uploading...
Home