I have a form button with an onclick event that runs a simple javascript function (adds 1 to a value).
I have to click the mouse button each time for this to run, is there any way of making it so if the mouse button is held down it runs it too, but every half a sec?
<script>
function incrementValue(id) {
var value = parseInt(document.getElementById(id).innerHTML);
value=++;
document.getElementById(id).innerHTML = value;
}
</script>
html
<input type="text" id="attk">
<input type="text" id="def">
<input type="button" onclick="incrementValue('attk')">
<input type="button" onclick="incrementValue('def')">
The following will repeat every 500ms while the button is pressed - and will increment a counter
JavaScript:
var intervalId; // keep the ret val from setTimeout()
function mousedownfunc(divid) {
intervalId = setInterval(runme, 500, divid);
}
function mouseupfunc() {
clearInterval(intervalId);
}
function runme(divid) {
document.getElementById(divid).innerHTML = parseFloat(document.getElementById(divid).innerHTML) + 1;
}
HTML :
<input type="button" onmousedown="mousedownfunc('counter')" value="clickme" onmouseup="mouseupfunc('counter')" /><br/>
<div id="counter">1</div>
Working example with counter -> http://jsfiddle.net/73uKk/1/
You can add an onmousedown event(http://www.w3schools.com/jsref/event_onmousedown.asp) to the button.
Then use setTimeout() function (http://www.w3schools.com/jsref/met_win_settimeout.asp)
<input type="submit" onmousedown="func1">
function func1(){
//yourcode;
setTimeout(func1,500);
}
Not sure about the right syntax in setTimout.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With