scott.schaffer scott.schaffer - 5 months ago 13
jQuery Question

alternate button text automatically without click

I would like alternate between 2 pieces of text on a button in 2 sec intervals. This is NOT a click event. I just want the button to rotate between 'click here' and 'download'. This is what Im trying with no luck:

<div class="assetClass customButton1_1Div" id="download_btn1">
<input type="button" class="customButton1_1" name="button1_1" value="click here" title="download_btn1" />
</div>

setInterval(toggle, 2000);
function toggle() {
document.getElementByName("button1_1").value = "download";
}

Answer

Something like this?

var cnt=0, arr = ['Click Here','Download'];
setTimeout(toggle, 1500);

function toggle() {
  $('.btn').val(arr[cnt]);
  cnt = (cnt > 0) ? 0 : 1;
  setTimeout(toggle, 1500);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div class="assetClass customButton1_1Div" id="download_btn1">
  <input type="button" class="btn" value="Download" />
</div>

Note that setInterval has certain drawbacks compared with a recursive setTimeout:

http://www.erichynds.com/blog/a-recursive-settimeout-pattern