I am creating a few pages for academic purposes and I want to hide the "Next" button for a certain amount of seconds. The problem is that once the page gets refreshed, the timer starts all over. I want it to continue after the page is refreshed and I want to improve the code that is already written rather than see a new solution.
<strong>
<input class="btn btn-primary btn-large btn-primary next-button" type="submit" value="Next"/>
<script>
var showButton = document.getElementsByClassName("btn btn-primary btn-large btn-primary next-button")[0];
var counter = 5;
var newElement = document.createElement("p");
newElement.innerHTML = "You can proceed to the subsequent page in " + counter + " seconds.";
var interval;
showButton.parentNode.replaceChild(newElement, showButton);
interval = setInterval(function() {
counter--;
if(counter < 0) {
newElement.parentNode.replaceChild(showButton, newElement);
clearInterval(interval);
} else {
newElement.innerHTML = "You can proceed to the subsequent page in " + counter.toString() + " seconds.";
}
}, 1000);
</script>
</strong>
I do understand the idea behind the localStorage but where exactly do I need to insert it? I am trying to insert it beside "var counter" but it does not do what I want.
You need localStorage
or cookies
to store data and use even after page reload.
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
UPDATE
After updated question, here is how you need to store and get counter
variable from localStorage
when you declared counter variable:
var counter = localStorage.getItem("counter");
counter = counter ? counter : 5 ; // if in store then that value otherwise 5 as default
You can detect page reload/refresh using javascript onbeforeunload
event and same time store the counter value for next use.
window.onbeforeunload = function() {
localStorage.setItem("counter", counter);
};
UPDATE-2
Here is a working fiddle that you can use:
Javascript is client-sided. It will reset on reload or any other thing.
A simple solution to your problem might be HTML5 storage
, or session storage
Example:
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
HTML web storage provides two objects for storing data on the client:
window.localStorage
- stores data with no expiration date window.sessionStorage
- stores data for one session (data is lost when the browser tab is closed) The localStorage Object
The localStorage object stores the data with no expiration date. The data will not be deleted when the browser is closed, and will be available the next day, week, or year.
More Documentation about LocalStorage Here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.