fudgepuppy fudgepuppy - 6 months ago 111
Javascript Question

Javascript Auto Refresh Toggle Checkbox

I want my visitors to be able to toggle an auto page refresh with a checkbox (no iframes).

This is the most similar code i found on Google, but it was created in 2004 and i cant seem to get it to work.

I am using this code on wordpress. So the issue may lie in ""timerRefresh.htm?Checked"" below, i dont know what to rename it to, as my WP page doesnt end with .html/.php/etc... it just ends with a "/"

p.s i know there are browser extensions for auto-reload, i am not looking for that.

Thank you!

var asdf = false;
function StartTime(){
if(asdf)clearTimeout(asdf)
asdf = setTimeout("RefreshPage()",5000);
}
function RefreshPage(){
clearTimeout(asdf)
if(document.Test.CB1.checked)
document.location.href= "timerRefresh.htm?Checked"
}
function LoadPage(){
var findCheck = document.location.href.split("?Chec");
if(findCheck.length == 2){
document.Test.CB1.checked=true;
StartTime()
}
}


 

<body onload="LoadPage()">
   <form name="Test">
     <input type="checkbox" name="CB1" onclick="StartTime()">
   </form>
 </body>

Answer

Try this:

HTML:

<input type="checkbox" onclick="toggleAutoRefresh(this);" id="reloadCB"> Auto Refresh</input>

JavaScript:

var reloading;

function checkReloading() {
    if (window.location.hash=="#autoreload") {
        reloading=setTimeout("window.location.reload();", 5000);
        document.getElementById("reloadCB").checked=true;
    }
}

function toggleAutoRefresh(cb) {
    if (cb.checked) {
        window.location.replace("#autoreload");
        reloading=setTimeout("window.location.reload();", 5000);
    } else {
        window.location.replace("#");
        clearTimeout(reloading);
    }
}

window.onload=checkReloading;

Demo: Auto Reload off | Auto Reload on
The demo includes console logging to let you know when auto reload is turned off or on, as well as when the page reloads, since it can easily reload so quickly that you don't notice it.