toggle button to start/stop refreshing my page - javascript

I'm trying to make sort of a toggle button to start and stop a page from refreshing itself but for some reason the stopping process isn't working. is my logic correct?
this is my code:
<button id = "toggleButton" onclick = "initRefresh()" > Stop Refresh </button>
<script>
function reloadUrl() {
window.location.replace(
[location.protocol, '//', location.host, location.pathname].join('')
);
}
function initRefresh() {
if ($('#toggleButton').text() == 'Start Refresh') {
$('#toggleButton').text("Stop Refresh");
t = window.setTimeout(reloadUrl, 45000);
} else {
$('#toggleButton').text("Start Refresh");
clearTimeout(t);
}
};
var t = window.setTimeout(reloadUrl, 45000);
</script>
the default option (on first load) is on. so when the user goes into the page for the first time 45 seconds later the page will refresh.
Thanks for the help.

I believe the problem comes from the initialization of the t variable.
You start a setTimeout when the page loads.
Change it to var t = null and the above code should work.

Your code (as in question) is working 100%.
But it will not work if placed your code inside $(document).ready event.

Related

Javascript function to show a hidden button with setTimeout not working in a PDF

I have an interactive PDF with a form field button called “Nav_Forward_Page_14” that is set to hidden. I want the button to be visible 10 seconds after the page containing the button loads; so on Page Properties (for the page with the button), I've tried adding the following Javascript on page load, but neither script is working:
setTimeout(function() {
this.getElementById("Nav_Forward_Page_14").style.display = "inline";
}, 10000);
Thinking that I may have the function wrong, I also tried:
setTimeout(function() {
this.getElementById("Nav_Forward_Page_14").display = display.visible;
}, 10000);
Please help me correct the function necessary to show the hidden button after a delay on page load in a PDF. Thank you in advance!
You can use document.body.onload = function(){} which will execute once the DOM body is loaded which is the same as putting your script on the bottom of your <body> tag.
I made the delay 3 seconds to not waste time, you can edit yourself.
Here is a more simplified example:
var delay = 3000;
document.body.onload = function() {
setTimeout(() => {
document.querySelector('button').style.display = 'inline';
}, delay);
}
button {
display: none;
}
<button>Next page</button>
Got this to work in the PDF when added as Javascript to page open:
function runImage() {
this.getField("Nav_Forward_Page_14").display = display.visible
}
run = app.setTimeOut("runImage()", 10000);

How to use setInterval to have Refresh on by default but off with a switch

I would like to use setInterval to control a refresh of my page. I would like to have it running by default (on when the page loads) but I need to be able to turn it off at certain times. So I've written what you see below. The problem is that the refresh is not on when the page first displays. It only comes on after I click the button twice to re-activate the update the setInterval controls.
My html button definition looks like this;
<button id="autoref" type="button" name="autoref" onclick="stopAutoRef();">Stop Auto Ref</button>
My stopAutoRef function looks like this;
function stopAutoRef() {
if ($("#autoref").text() == "Stop Auto Ref") {
$("#autoref").html('Start Auto Ref'); // You see this if Refresh is not automatically happening
clearInterval();
}else {$("#autoref").html('Stop Auto Ref'); // You see this if Refresh is automatically happening
setInterval(function() {showActivities(document.getElementById("select1").value);}, 60000);
}
}
setInterval returns an ID which must be passed to clearInterval to stop it. You'd also want to call your function, startAutoRef(), immediately in addition to on click to initiate the default behavior of refreshing.
var autoRefId = null;
function stopAutoRef() {
if (autoRefId !== null) {
$("#autoref").html('Start Auto Ref'); // You see this if Refresh is not automatically happening
clearInterval(autoRefId);
autoRefId = null;
} else {
$("#autoref").html('Stop Auto Ref'); // You see this if Refresh is automatically happening
autoRefId = setInterval(function() {showActivities(document.getElementById("select1").value);}, 60000);
}
}
stopAutoRef();
clearinterval generally requires a argument of which function to stop. so try this maybe?
try this:
HTML:
<button id = 'b' onclick = 'stop(this)' value = 'true'>Stop ref</button>
Javascript:
var myfunc = setInterval(function(){
location.reload();
},1000);;
function stop(button){
if(button.innerHTML == 'Stop ref'){
button.innerHTML = 'Start ref';
clearInterval(myfunc);
}
else{
button.innerHTML = 'Stop ref';
myfunc = setInterval(function(){
location.reload();
},1000);;
}
}

Onclick load page in Div and change text

I have this button and what it currently does is onclick it changes the text from text1 to text2 Below is the button and the script which achieves this.
Button
<button type="button" id="buttonsend" style="margin-top:-7px;" class="btn btn-default">
<span>text 1</span>
<span style="display:none">text 2</span>
</button>
<div id="load"></div>
Javascript
$('#buttonsend').click(function() {
$('span',this).toggle();
});
What I want it to also do is load a page in the #load div only once its clicked and also refresh the page loaded in the div every 10 seconds.
Example
Once the button is clicked the text is changed to text2 and the #load div loads the demo.html page and refreshes this page every 10 seconds. once the button is clicked again the #load div stops refreshing the page and the text returns to text1. I'm really sorry for making this almost a request but I'm having some difficulties achieving this.
I have coded this script below which refreshes a page loaded in a div every 10 seconds however it loads before the button is clicked so I'm not sure how to get it work once the button is clicked and when the button is clicked again to stop refreshing. Thankyou.
Refresh Script
$(document).ready(function(){
setInterval(function(){
$("#load").load('/demo.html')
}, 10000);
});
You could use a boolean variable for this, which you toggle when the button is clicked, and in your interval callback you just check whether it is set before reloading:
var reload = false;
$('#buttonsend').click(function() {
reload = !reload;
// other actions...
});
$(document).ready(function(){
setInterval(function(){
if (reload) $("#load").load('/demo.html')
}, 1000); // or 10000 if you want 10 sec.
});
Try using variables to keep the state of your button:
$(document).ready(function(){
var button_state = 'state1';
function toggleButtonState() {
if(button_state == 'state1') button_state == 'state2';
else button_state == 'state1';
}
$('#buttonsend').click(function() {
toggleButtonState();
$('span',this).toggle();
});
setInterval(function(){
if(button_state == 'state2') $("#load").load('/demo.html');
}, 10000);
});
While Wikiti's and trincot's answers are correct, I believe it's better to disable the loop while it's not used, using clearInterval. This will make sure that content will load the moment when user presses the button - otherwise, like in Wikiti's and trincot's answers, user may miss the loop iteration and click the button when there are 9 seconds to the next iteration, so he will have to wait 9 seconds for the content to begin loading.
$(document).ready(function(){
var timer = "none";
function startLoop() {
timer = setInterval(function(){
$("#load").load('/demo.html');
}, 10000);
}
function toggleButtonState() {
if (timer === "none") { startLoop(); }
else { clearInterval(timer); timer = "none"; }
}
$('#buttonsend').click(function() {
toggleButtonState();
$('span',this).toggle();
});
});
If you give text2 and id you can see if it is visible or not, or wrap it in a div, I had a similar need to have a countdown and to pause when the div was visible. Can't remember where I took the below from. Basically counts down from 300, but pauses when the div called 'callUpdateWrap' is visible. I also had it update a timer on the page itself (see way down the page):
JS:
function refreshpage(interval, countdownel, totalel){
var countdownel = document.getElementById(countdownel)
var totalel = document.getElementById(totalel)
var timeleft = interval+1
var countdowntimer
function countdown(){
if (!$('#callUpdateWrap').is(':visible')) {
timeleft--
}
countdownel.innerHTML = timeleft
if (timeleft == 0){
clearTimeout(countdowntimer)
window.location.reload()
}
countdowntimer = setTimeout(function(){
countdown()
}, 1000)
}
countdown()
}
window.onload = function(){
refreshpage(300, "countdown") // refreshpage(duration_in_seconds, id_of_element_to_show_result)
}
HTML:
<h2>Page will Refresh in <b id="countdown"></b> seconds</h2>
Quick Edit:
If you need the timer to reset, where the div is checked if visible, you could add an else to set the time back to 10.

Page re-load on AJAX return looses focus on button

I have a button click action upon which I make AJAX call to update a field. After the AJAx returns, I am doing this -
document.location.reload(true);
The page reloads, however, the focus is not returning to the button. Can you suggest a means where I can reload/refresh the page and the focus returns on the button to click again?
I have updated my AJAX code here, please tell me how to modify this -
<input type="button" name="IncreaseMyDate" id="myDate" value="Increase" onclick="updateMyDate('<%=myDate%>')"/>
function updateMyDate(mywDate)
{
XMLHttpObj_myDate = CreateHttpObject();
if(XMLHttpObj_myDate == null){
alert("HTTP Request not supported");
return;
}
var itemId = document.getElementById("itemId").value;
document.getElementById("myDate").setAttribute("disabled",true) ;
var url ="IncreaseMyDate.jsp?action=update&myDate="+reviewDate;
document.getElementById("myDate").style.cursor = "not-allowed";
XMLHttpObj_myDate.onreadystatechange=fillMyDate;
XMLHttpObj_myDate.open("GET",url);
XMLHttpObj_myDate.send(null);
return false;
}
function fillMyDate(){
if(XMLHttpObj_reviewDate.readyState == 4 || XMLHttpObj_myDate.readyState == "complete"){
document.getElementById("myDate").style.cursor = "pointer";
document.getElementById(myDate").innerHTML = XMLHttpObj_myDate.responseText;
document.location.reload(true);
}
}
Why do you do the page reload? The big advantage of making Ajax calls is that they avoid the need to reload the page. You could just do all the Ajax work server-side when you are reloading the page.
You need to pass a variable to the new page load that indicates what button should have the focus. Your page reload doesn't know about what was happening client-side before. Pass the id of the button in the query string and then use it to find the button again and set the focus.
You could store the button's id in sessionStorage, and then check when the page loads to reapply the focus if applicable.
The following page worked in my tests:
<body onload="body_onload();">
<button id="buttonA" onclick="button_click(this);">Button A</button><br/>
<button id="buttonB" onclick="button_click(this);">Button B</button><br/>
<button id="buttonC" onclick="button_click(this);">Button C</button><br/>
</body>
<script>
function body_onload() {
var buttonId = sessionStorage["buttonId"];
if (buttonId) {
document.getElementById(buttonId).focus();
}
}
function button_click(button) {
sessionStorage["buttonId"] = button.id;
document.location.reload(true);
}
</script>

Jquery timeout code not re-running after first time user extends session

I wrote a Jquery function that blacks out the screen after a certain amount of inactivity, creates a pop-up that allows the user to click a button to stay logged in, and logs them out (closing the application window) if they do not respond in time.
The environment is ASP.NET (VB). We don't technically use master pages, but we do have a parent page in which our header, footer and nav reside, and my Jquery code is called from that window, loaded via an IFrame.
I've got a function in the child window that reports activity (currently keydown, mousedown and blur) to the parent window, and resets the timer. My code seems to be working fine, except in one scenario. If the user is prompted with the timeout warning, and then they click the button to continue their session, if they take no action on the page (mouseclick, keydown, etc.) then the timeout code is not running a second time.
Here is my main jquery function:
function pop_init() {
// show modal div
$("html").css("overflow", "hidden");
$("body").append("<div id='popup_overlay'></div><div id='popup_window'></div>");
//$("#popup_overlay").click(popup_remove); // removed to make sure user clicks button to continue session.
$("#popup_overlay").addClass("popup_overlayBG");
$("#popup_overlay").fadeIn("slow");
// build warning box
$("#popup_window").append("<h1>Warning!!!</h1>");
$("#popup_window").append("<p id='popup_message'><center>Your session is about to expire. Please click the button below to continue working without losing your session.</center></p>");
$("#popup_window").append("<div class='buttons'><center><button id='continue' class='positive' type='submit'><img src='images/green-checkmark.png' alt=''/> Continue Working</button></center></div>");
// attach action to button
$("#continue").click(session_refresh);
// display warning window
popup_position(400, 300);
$("#popup_window").css({ display: "block" }); //for safari using css instead of show
$("#continue").focus();
$("#continue").blur();
// set pop-up timeout
SESSION_ALIVE = false;
window.setTimeout(popup_expired, WARNING_TIME);
}
Here is the code from the parent window:
<script language="javascript" type="text/javascript">
var timer = false;
window.reportChildActivity = function() {
if (timer !== false) {
clearTimeout(timer);
}
//SESSION_ALIVE = true;
timer = window.setTimeout(pop_init, SESSION_TIME);
}
</script>
Here is the code from the child window:
<script type="text/javascript">
$(document).ready(function() {
window.parent.reportChildActivity();
});
</script>
<script type="text/javascript">
$(document).bind("mousedown keydown blur", function() {
window.parent.reportChildActivity();
});
The last script runs in a file (VB.NET ascx file) that builds the header/menu options for every page in our system.
The last line in the pop_init function clearly should be re-starting the timer, but for some reason it doesn't seem to be working.
Thanks for any help and insight you may have.
Forgot to add my code for the session_refresh function:
function session_refresh() {
SESSION_ALIVE = true;
$(".buttons").hide();
$("#popup_message").html("<center><br />Thank you! You may now resume using the system.<br /></center>");
window.setTimeout(popup_remove, 1000);
$("#popup_window").fadeOut("slow", function() { $('#popup_window,#popup_overlay').trigger("unload").unbind().remove(); });
var timer = false;
window.reportChildActivity = function() {
if (timer !== false) {
clearTimeout(timer);
}
timer = window.setTimeout(pop_init, SESSION_TIME);
}
}
use this: http://www.erichynds.com/jquery/a-new-and-improved-jquery-idle-timeout-plugin/
You need to restart your timer after the user clicks the button.
Well, I seem to have fixed the problem by changing this:
var timer = false;
window.reportChildActivity = function() {
if (timer !== false) {
clearTimeout(timer);
}
timer = window.setTimeout(pop_init, SESSION_TIME);
}
to this:
if (timer !== false) {
clearTimeout(timer);
}
timer = window.setTimeout(pop_init, SESSION_TIME);
I didn't need to re-declare the reportChildActivity function as I was.

Categories