Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Repeatedly Auto Refresh Webpage with an ON-OFF Buttons

I would like to use Javascript to auto-refresh my webpage while users can choose to turn on/turn off the auto-refresh function with two different buttons (Please be aware that the buttons are using <label> and <input> tag). I have tried my best to write the code but I still do not know how to link up these two codes so that it can function correctly.

Also, if user choose the buttons of auto-refresh ON, I want to keep auto refresh continuously after its first load instead of just auto refreshing only once.

Would you please help me to correct my codes, please? Thank you.

The code for ON and OFF buttons (two individual buttons):

<div class="page-header-actions" data-toggle="buttons" role="group">
  <label class="btn btn-outline btn-primary active">
    <input type="radio" name="options" autocomplete="off" value="autorefreshoff" checked />
    <i class="icon wb-check text-active" aria-hidden="true"></i> Auto Refresh OFF
  </label>
  <label onClick="startrefreshon" class="btn btn-outline btn-primary">
    <input type="radio" autocomplete="off" value="autorefreshon" />
    <i class="icon wb-check text-active" aria-hidden="true"></i> Auto Refresh ON
  </label>
</div>

The code for auto-refresh function:

<script type='text/javascript'>
setTimeout(function(){
   window.location.reload(1);
}, 5000);
</script>
like image 485
Dennis Avatar asked Sep 19 '25 02:09

Dennis


1 Answers

Here are a few things you need to do:

  1. Both the input type="radio" should have same name.
  2. Give the 'auto refresh on' button an ID, so that you can reference it easily in JavaScript code (say auto-refresh-checkbox).
  3. Write a reload function that checks if the checkbox is checked

code:

function reloadPage(){
  var refreshEnabled = document.getElementById('auto-refresh-checkbox');
  if(refreshEnabled.checked) {
    window.location.reload(1);
  }
}
  1. Then call this function via setInterval

setInterval(reloadPage, 5000);


PS: The checked "auto refresh" radio will lose it's value on page reload, so you might have to save the value using localStorage or something else.

like image 145
vsr Avatar answered Sep 20 '25 16:09

vsr