How to Change a Button Text on Click Using LocalStorage in Javascript?


JavaScript is a famous programming language that is one of the core languages of the World Wide Web (WWW) alongside HTML and CSS. It allows the programmer to capture events and modify the Document Object Model (DOM). In this article we are going to see how we can make use of JavaScript to change the text of the button whenever it is clicked with the help of localStorage.

localStorage

The localStorage is a read−only property of the window interface that allows the user to store data. The saved information is kept between browser sessions.

The localStorage property is like sessionStorage, but the catch is that the data persists even when the page session has ended.

We can get a localStorage item using the getItem() method. It has the following syntax:

localStorage.getItem(‘key’);

We can also set a localStorage item. This can be done using the setItem() method. It has the following syntax:

localStorage.setItem(‘key’,’value’);

Example

Step 1: First, we will define the HTML code.

<!DOCTYPE html>
<html>
<head>
   <title>How to change a button text on click using localStorage in Javascript?</title>
</head>
<body>
   <h4>How to change a button text on click using localStorage in Javascript?</h4>
   <div>
      <button id="main">CLICK ME!</button>
   </div>
</body>
</html>

Step 2: Now we will provide some styling to the elements with the help of CSS.

<style>
   #main {
      width: 20%;
      height: 50px;
      border-radius: 10px;
   }
</style>

Step 3: Now we will write the logic for changing the text on button click.

<script>
let button=document.getElementById('main');
localStorage.setItem('buttonText','CLICKED!');
button.onclick=function(){
   button.textContent=localStorage.getItem('buttonText');
}
</script>

Here is the complete code:

<!DOCTYPE html>
<html>
<head>
   <title>How to change a button text on click using localStorage in Javascript?</title>
   <style>
      #main {
         width: 20%;
         height: 50px;
         border-radius: 10px;
      }
   </style>
</head>
<body>
   <h4>How to change a button text on click using localStorage in Javascript?</h4>
   <div>
      <button id="main">CLICK ME!</button>
   </div>
   <script>
    let button=document.getElementById('main');
    localStorage.setItem('buttonText','CLICKED!');
    button.onclick=function(){
       button.textContent=localStorage.getItem('buttonText');
    }
   </script>
</body>
</html>

Conclusion

In this article we saw how we can make use of getItem() and setItem() methods of localStorage to access storage items. Combining this with the knowledge of the onClick event we were able to change the text of the button element whenever it was clicked.

Updated on: 12-Sep-2023

196 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements