auto reload div with toggle checkbox and user selected interval - javascript

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.

Related

Auto refreshing page with saved input

I'm trying to make a JSP that refresh itself every 2scd approximately and keep what the user tip in input form.
My idea was to save the input with javascript, add them to the URL and refresh the page, then retrieve and set the input.
This is my JS code :
$(document).ready(function () {
function refreshPage(){
var mapValue = new Array();
var mapName = new Array();
var i = 0;
$(".positionInput").each(function() {
mapValue[i] = $(this).val();
mapName[i] = $(this).attr("name");
i++;
});
var parameters = "";
for(i = 0; i < mapName.length; i++){
if(mapValue[i] != ""){
parameters += "?" + mapName[i] + "=" + mapValue[i];
}
}
window.location.href = "http://localhost:8080/drawinguess/waitingplayer.jsp" + parameters;
setTimeout(refreshPage, 2000); //execute itself every 2s
}
refreshPage();
});
But the timer get crazy (even with 1mn delay), it refresh itself as fast as he can with window.location.href (without this, it's working fine)
Thanks in advance if you have any other idea or if I'm making something wrong
You could try and use local storage for this. The best way would be that instead of refreshing the entire page, you only refresh what is needed by having services set up and using an async function like fetch() to hit those services and update the page.

Why/How to fix selected option in DOM different from screen in IE11

I have a page that has JavaScript that executes history.go(-1); return false; to go to a previous page when a "Return" button is pushed. The page displays the correct selected option on the initial page load but when going to the next page that has the "Return" button and then going back, the selected option displayed on the screen becomes a random value that is not the same as what the DOM shows. Below are screenshots of the progression and then my sortSelect() code at the bottom. This issue does not occur in Edge or Chrome but does in IE 11.
I'm ultimately wanting to know how to remedy this issue such that what is displayed on the screen reflects what the DOM is saying is the selected option.
Before Sort on initial page load (correct option displays):
After Sort on initial page load (correct option displays):
Before Sort after history.go(-1) from next page (incorrect option displays):
After Sort after history.go(-1) from next page (incorrect option displays):
Sort Select method:
$.fn.sortSelect = function() {
this.each(function(index, selectElement) {
if (selectElement && selectElement.tagName.toUpperCase() === "SELECT") {
var val = $(selectElement).val();
// get the child options
var options = $(selectElement).children('option');
// sort'em
options.sort(function(a, b) {
if ( ! a.text) {
a.text = "";
}
if ( ! b.text) {
b.text = "";
}
if (a.text.toLowerCase() > b.text.toLowerCase()) {
return 1;
} else if (a.text.toLowerCase() < b.text.toLowerCase()) {
return -1;
} else {
return 0;
}
});
// purge the select element and append the sorted options.
$(selectElement).empty();
$(selectElement).append(options);
$(selectElement).val(val);
}
});
};

Slidetoggle to retain current state when page is refreshed

I have this code, which works but goes back to initial closed state whenever I reload or refresh page. I want retain last toggle state even after page reload. Can't seem to get my head around this problem.
My code is:
var $answers = $('.contentbar');
$(".titlebar").click(function () {
var $ans = $(this).next(".contentbar").stop(true).slideToggle(500);
$answers.not($ans).filter(':visible').stop(true).slideUp();
})
There's a plugin called jQuery.cookie. Using that you can check if there's already a user-set accordion and based on the preference, you can show / hide stuff by default.
var $answers = $('.contentbar');
$(".titlebar").click(function () {
if (!$.cookie('contentbar'))
var $ans = $(this).next(".contentbar").stop(true).slideToggle(500);
else
{
var $ans = $($.cookie('contentbar')).next(".contentbar").stop(true).slideToggle(500);
$.cookie('contentbar', this);
}
$answers.not($ans).filter(':visible').stop(true).slideUp();
});

display message javascript while a calculation is being made

I have been looking around and I cannot seem to figure out how to do this, although it seems like it would be very simple.(mobile development)
What I am trying to do is display a message (kind of like an alert, but not an alert, more like a dialog) while a calculation is being made. Simply like a Loading please wait. I want the message to appear and stay there while the calculation is being done and then be removed. I just cannot seem to find a proper way of doing this.
The submit button is pressed and first checks to make sure all the forms are filled out then it should show the message, it does the calculation, then hides the message.
Here is the Calculation function.
function scpdResults(form) {
//call all of the "choice" functions here
//otherwise, when the page is refreshed, the pulldown might not match the variable
//this shouldn't be a problem, but this is the defensive way to code it
choiceVoltage(form);
choiceMotorRatingVal(form);
getMotorRatingType();
getProduct();
getConnection();
getDisconnect();
getDisclaimer();
getMotorType();
//restore these fields to their default values every time submit is clicked
//this puts the results table into a known state
//it is also used in error checking in the populateResults function
document.getElementById('results').innerHTML = "Results:";
document.getElementById('fuse_cb_sel').innerHTML = "Fuse/CB 1:";
document.getElementById('fuse_cb_sel_2').innerHTML = "Fuse/CB 2:";
document.getElementById('fuse_cb_result').innerHTML = "(result1)";
document.getElementById('fuse_cb_res_2').innerHTML = "(result2)";
document.getElementById('sccr_2').innerHTML = "<b>Fault Rating:</b>";
document.getElementById('sccr_result').innerHTML = "(result)";
document.getElementById('sccr_result_2').innerHTML = "(result)";
document.getElementById('contactor_result').innerHTML = "(result)";
document.getElementById('controller_result').innerHTML = "(result)";
//Make sure something has been selected for each variable
if (product === "Choose an Option." || product === "") {
alert("You must select a value for every field. Select a Value for Product");
**************BLAH************
} else {
//valid entries, so jump to results table
document.location.href = '#results_a';
******This is where the message should start being displayed***********
document.getElementById('motor_result').innerHTML = motorRatingVal + " " + motorRatingType;
document.getElementById('voltage_res_2').innerHTML = voltage + " V";
document.getElementById('product_res_2').innerHTML = product;
document.getElementById('connection_res_2').innerHTML = connection;
document.getElementById('disconnect_res_2').innerHTML = disconnect;
if (BLAH) {
}
else {
}
populateResults();
document.getElementById('CalculatedResults').style.display = "block";
} //end massive else statement that ensures all fields have values
*****Close out of the Loading message********
} //scpd results
Thank you all for your time, it is greatly appreciated
It is a good idea to separate your display code from the calculation code. It should roughly look like this
displayDialog();
makeCalculation();
closeDialog();
If you are having trouble with any of those steps, please add it to your question.
Computers are fast. Really fast. Most modern computers can do several billion instructions per second. Therefore, I'm fairly certain you can rely on a a setTimeout function to fire around 1000ms to be sufficient to show a loading message.
if (product === "Choose an Option." || product === "") {
/* ... */
} else {
/* ... */
var loader = document.getElementById('loader');
loader.style.display = 'block';
window.setTimeout(function() {
loader.style.display = 'none';
document.getElementById('CalculatedResults').style.display = "block";
}, 1000);
}
<div id="loader" style="display: none;">Please wait while we calculate.</div>
You need to give the UI main thread a chance to render your message before starting your calculation.
This is often done like this:
showMessage();
setTimeout(function() {
doCalculation();
cleanUp()
}, 0);
Using the timer allows the code to fall through into the event loop, update the UI, and then start up the calculation.
You're already using a section to pop up a "results" page -- why not pop up a "calculating" page?
Really, there are 4,000,000 different ways of tackling this problem, but why not try writing a "displayCalculatingMessage" function and a "removeCalculatingMessage" function, if you don't want to get all object-oriented on such a simple thing.
function displayCalculatingMessage () {
var submit_button = getSubmitButton();
submit_button.disabled = true;
// optionally get all inputs and disable those, as well
// now, you can either do something like pop up another hidden div,
// that has the loading message in it...
// or you could do something like:
var loading_span = document.createElement("span");
loading_span.id = "loading-message";
loading_span.innerText = "working...";
submit_button.parentElement.replaceChild(loading_span, submit_button);
}
function removeCalculatingMessage () {
var submit_button = getSubmitButton(),
loading_span = document.getElementById("loading-message");
submit_button.disabled = false;
loading_span.parentElement.replaceChild(submit_button, loading_span);
// and then reenable any other disabled elements, et cetera.
// then bring up your results div...
// ...or bring up your results div and do this after
}
There are a billion ways of accomplishing this, it all comes down to how you want it to appear to the user -- WHAT you want to have happen.

Javascript - How to disable the print dialog after first show?

On one of our pages the user has the option to print a selected list of html pages. This is how it is at the moment
var rowcount = FrmMain.RowCount;
var frame = FrmMain.Frame;
for(i=1;i<=rowcount;i++)
{
var obj = FrmMain.elements("chk_" + i);
if(obj.checked)
{
frame.src = FrmMain.elements("hpath" + i).value;
window.frames[frame.id].focus();
window.frames[frame.id].print();
}
}
Now this works fine. The problem is that on each loop the print dialog box is displayed and the user has to click print.
Basically, what I'm asking is whether that is a way to supress this dialog. It must appear at the first time but hide thereafter. Some thing like below
var show = true;
...
{
...
{
...
if(show)
{
window.frames[frame.id].focus();
window.frames[frame.id].print();
show = false;
}
else
{
window.frames[frame.id].focus();
window.frames[frame.id].printwithoutdialog();
}
}
}
I hope I've been clear. Thanks in advance.
For security / privacy reasons, this is impossible.
Otherwise, ads would automatically print their brochures.
Instead, you can combine all of the pages into a single frame.
Some browsers have an option bypass the dialog, but it can't be done in javascript.

Categories