Tips for avoiding a button reverting to its original state upon page refresh

I have a button with the ID #first that, when clicked, is replaced by another button with the ID #second. However, if I refresh the page after clicking on the second button, it goes back to displaying the first button. Is there a way to make sure that the second button remains displayed even after a page refresh?

<!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">First Button</button>
  </body>
</html>

Answer №1

Create a persistent cookie to remember the status of the button, then retrieve and display this saved state when the document is ready.

Answer №2

Utilize local storage and retrieve the button state upon window load.

For a demonstration, refer to : http://www.w3schools.com/html/html5_webstorage.asp

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

You can modify this as follows :

      // Save
      localStorage.setItem("buttonState", "Second");
      // Get
      var buttonState = localStorage.getItem("buttonState");

In your scenario :

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

In your example, when changing the state to second, save the state as shown (setItem) and then fetch it upon document ready or window load.

Here is an example fiddle demonstrating its functionality: https://jsfiddle.net/wg7xL4sa/2/

Please note that I have commented out the localStorage.clear(). This can be used to clear your local storage if needed.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues with Angular route links not functioning correctly when using an Array of objects

After hard coding some routerLinks into my application and witnessing smooth functionality, I decided to explore a different approach: View: <ul class="list navbar-nav"></ul> Ts.file public links = [ { name: "Home&quo ...

Playing out the REST endpoint in ExpressJS simulation

Suppose I have set up the following endpoints in my ExpressJS configuration file server.js: // Generic app.post('/mycontext/:_version/:_controller/:_file', (req, res) => { const {_version,_controller,_file} = req.params; const ...

Tips for gathering all links from a JSON object

When dealing with a JSON object of any structure, simple or complex, what would be the most efficient way to extract all URLs from the data and store them in an array for iteration in JavaScript? { "url": "https://example.com:443/-/m ...

Even though the Spotify API JSON response may be undefined, I am still able to log it using console.log()

Trying to utilize Spotify's Web Player API in order to retrieve the 'device_id' value has been a challenge. The documentation states that the server-side API call I am supposed to make should result in a 'json payload containing device ...

What could be the reason behind my inability to initiate this PHP file through jQuery/AJAX?

I'm experiencing an issue with a piece of PHP code (located at ../wp-content/plugins/freework/fw-freework.php). <div id="new-concept-form"> <form method="post" action="../wp-admin/admin.php?page=FreeWorkSlug" class="form-inline" role ...

Navigating through tabs in a Meteor application: How to maintain the active tab when using the back button

I am working on a multi-page meteor application where each page includes a navigation template. To switch between pages, I am using iron-router. The user's current page is indicated by setting the appropriate navigation link's class to 'ac ...

Tips for implementing personalized command buttons in Kendo Grid with AJAX request utilizing JavaScript

I am struggling with implementing custom command buttons in a Kendo grid that makes an AJAX call using JavaScript to call a web API post action with dynamic parameters (start, stop, restart) behind button clicks. datasource dataSource = new ken ...

Unable to perform updates for personalized fonts

I've been trying to incorporate custom fonts into my website, but I seem to be facing difficulties in actually implementing them. Could someone please let me know if I am doing it correctly? .pattern{ background:rgba(0,0,0,.5) url(../images/pattern ...

the click event fails to trigger when the id or class is modified

Hey there, I'm new to working with jquery and I've encountered a problem. Here's the code snippet: http://jsfiddle.net/8guzD/ $('#test.off').click(function(){ $(this).removeClass('off').addClass('on'); }) ...

skip every nth element in the array based on the specified value

The Challenge I'm currently working on a graph that relies on an array of data points to construct itself. One major issue I've encountered is the need for the graph to be resizable, which leads to the necessity of removing certain data points ...

Tips on extracting the image URL after uploading via Google Picker

I'm currently implementing the Google Drive File Picker on my website for file uploading. Everything seems to be working well, except I am facing an issue with retrieving the image URL for images uploaded through the picker. Below is my current JavaSc ...

Elements that are positioned in a single line in a text

I am experimenting with a layout where each item is displayed in a single line, with the width of the items determined by their content. The desired output looks like this: Intended result: (This feature is only supported in modern browsers) .item { ...

Automatically organize <mat-list-item> elements within a <mat-list> container

Here is the code snippet: <div> <mat-list fxLayout="row" dense> <mat-list-item *ngFor="let label of labelsList"> <!-- just an array of strings --> <button mat-button> ...

"Exploring the power of Ajax: a guide to automatically refreshing the response every

I am struggling to understand why this snippet of code isn't working as expected. The div updates when using .html, but not with my custom script. In my setup, I have two files: index.php and test.php The index file looks like this: $(document).rea ...

The functionality of a custom control's jQuery code is not functioning properly following a postback

I'm currently developing a custom control that generates jQuery validation scripts for controls with changing validation rules based on configuration. It's necessary for the validation to be client-side due to large postbacks and slow, low-bandwi ...

Show all entries belonging to a specific ID on individual rows for each ID using PHP

I have a table generated from inner joins that displays different articles associated with outfit IDs. id_outfit | name | article ---------------------------------------- 56 | one | shoe.png 56 | one | dress.png 56 | one ...

What is the best way to modify the state of a nested component?

I am facing a challenge in my React project where I have two buttons in my App.js. When either of the buttons is clicked, I want to change the current state (list) to display in descending order based on the button pressed (order by date or order by upvo ...

Switch up image transitions using Javascript

I have already completed the css and html structure for my project. However, I am encountering issues with the JavaScript functionality. I really like the image effect on this website: (the blue one). I have attempted to replicate it here: , but have bee ...

How can I utilize jQuery to iterate through every anchor tag on an HTML page?

I am looking to reference all anchor tags on the page that have a parent h2 tag. To achieve this, I need to iterate through each anchor tag that has a parent h2 and add an attribute using jQuery. <body> <h1>not me</h1> <a href ...

The collapse component from bootstrap is not visible due to an overlapping button

I am currently working on a responsive calendar featuring full-width buttons for events, accompanied by additional information displayed using the collapse component below. However, I am facing an issue where the button overlaps with other elements, preven ...