Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript onclick repeat

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?

CURRENT CODE

<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')">
like image 851
user1022585 Avatar asked Mar 21 '26 23:03

user1022585


2 Answers

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/

like image 121
Manse Avatar answered Mar 24 '26 11:03

Manse


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.

like image 44
lvil Avatar answered Mar 24 '26 12:03

lvil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!