I have a chart that is dynamically created every time my page loads. I have it in a <div id="plot"></div> block. I would like to give the user the ability to toggle auto refresh on/off AND select the refresh rate. There are lots closely related solutions to this, but none that combines this and I'm struggling. For toggling a full reload, I'm using this example. This works well. However I can't figure out how to extend it to let the user select a interval from something like:
<select name="interval" id="interval">
<option value="1000">1</option>
<option value="2000">2</option>
<option value="5000">5</option>
<option value="10000">10</option>
</select>
I seem to both not know how to pass that result into the javascript and make it remember the interval after the reload. I'm guessing I need to not only pass it into the javascript, but somehow cancel the current timeout and reset it to the new value?
Maybe do something simple like pass in a second parameter of the interval select id in the onClick event like:
<input type="checkbox" onclick="toggleAutoRefresh(this, 'interval');" id="reloadCB"> Auto Refresh
Then in the JS set a new variable with the interval selection and if the page reloads include the interval time after #autoreload and pass it between reloads in the anchor hash:
var reloading;
$(document).ready(function () {
$('#interval').change(function () {
if (document.getElementById("reloadCB").checked) {
var intervalSelection = $(this).find(":selected").val();
window.location.replace("#autoreload-" + intervalSelection);
reloading = setTimeout("window.location.reload();", intervalSelection);
} else {
window.location.replace("#");
clearTimeout(reloading);
}
});
});
function checkReloading() {
if (window.location.hash.substring(0, 11) == "#autoreload") {
var intervalSelection = window.location.hash.substring(12, window.location.hash.length);
reloading = setTimeout("window.location.reload();", intervalSelection);
document.getElementById("reloadCB").checked = true;
var intervalSelect = document.getElementById('interval');
var intervalOptions = intervalSelect.options.length;
for (var i = 0; i < intervalOptions; i++) {
if (intervalSelect.options[i].value == intervalSelection) {
intervalSelect.options[i].selected = true;
break;
}
}
}
}
function toggleAutoRefresh(cb, intervalID) {
var intervalSelection = $('#' + intervalID).find(":selected").val();
if (cb.checked) {
window.location.replace("#autoreload-" + intervalSelection);
reloading = setTimeout("window.location.reload();", intervalSelection);
} else {
window.location.replace("#");
clearTimeout(reloading);
}
}
window.onload = checkReloading;
Haven't tested any of this and probably not the most elegant solution but first thing that came to mind.
Edit: Added some code to set drop down to value passed through hash tag as well as some JQuery to detect change of value on drop down and set new interval time.