Patrick Patrick - 10 days ago 5
HTML Question

javascript reload html page only when checkbox is checked

I would like to reload my page every x seconds if a checkbox is checked.

I found a code snipped for the reload and added an if statement.

But it doesn't work. The script only works without the if statemant.
What do I miss?

<!-- Reload page-->
setTimeout(function()
{
if (document.getElementById('CheckBoxReloadPage').checked)
{
location.reload(true);
document.getElementById("CheckBoxReloadPage").checked = true;
}
},
5000);




Thanks

Patrick

Answer

Your page is correctly reloaded after 5 seconds, but only if you checked the checkbox in the first 5 seconds after your page has loaded.

If you want the check to occur every 5 seconds instead of 5 seconds from now, change setTimeout to setInterval.

Then, as you may imagine, when your page reloads, everything will be back to the way it was - including the checkbox. You will have to store the state of your checkbox in, say, the session storage and set it to your checkbox upon loading:

// Gets the reference of the checkbox once and for all
var myCheckbox = document.getElementById('CheckBoxReloadPage');

// Sets the initial value of the checkbox to the stored state
myCheckbox.checked = sessionStorage.getItem('checkbox-state');

// Listen to every change on the checkbox
myCheckbox.addEventListener('change', function (event) {
    // Store the state of the checkbox to the session storage
    sessionStorage.setItem('checkbox-state', event.target.checked);
});

setInterval(function() {
    if (myCheckbox.checked) {
        location.reload(true);
    }
}, 5000);