user3398900
user3398900

Reputation: 845

How to prevent a button from going to original state when refreshed

I have a button #first which upon click is replaced with #second. After getting the second button and if I refresh the page I am going back to the first button. If I want my button to be the second button even after refresh how can I achieve this? Thank in advance

<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script>
      $(document).ready(function() {
        $("button").click(function() {
          $("#first").replaceWith('<button id="second">Second Button</button>');
        });
      });
    </script>
  </head>
  <body>
    <button id="first">firstbutton</button>
  </body>
</html>

Upvotes: 0

Views: 181

Answers (2)

thatOneGuy
thatOneGuy

Reputation: 10612

Use local storage and on window load just get the button state from there.

Example from : http://www.w3schools.com/html/html5_webstorage.asp

// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");

You could change this to :

      // Store
      localStorage.setItem("buttonState", "Second");
      // Retrieve
      var buttonState = localStorage.getItem("buttonState");

So in your case :

      var buttonState = localStorage.getItem("buttonState");   
      $(document).ready(function() { //on document ready
        if(buttonState){ //check if buttonState exists
            if(buttonState === 'Second'){ //if button state = second
              //logic to change state to second
              $("#first").replaceWith('<button id="second">Second Button</button>');
            }
    }
        $("button").click(function() {
          $("#first").replaceWith('<button id="second">Second Button</button>');
          localStorage.setItem("buttonState", "Second");
        });
        }

So in your example, if you change state to second, save the state like about (setItem) and then retrieve that on document ready or window load.

Here is an example fiddle of it working : https://jsfiddle.net/wg7xL4sa/2/

Notice I have commented out the localStorage.clear(). Use this to reset your local storage.

Upvotes: 1

abhinavchat
abhinavchat

Reputation: 93

set a cookie to persist the state of button and on document.ready,fetch the saved state and display it as such.

Upvotes: 2

Related Questions