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

JavaScript provides powerful tools to create interactive web pages. In this article, we'll learn how to change a button's text when clicked and persist that change using localStorage, so the new text remains even after refreshing the page.

What is localStorage?

The localStorage is a read-only property of the window interface that allows you to store data permanently in the user's browser. Unlike sessionStorage, data stored in localStorage persists even when the browser session ends, making it perfect for remembering user preferences.

localStorage Methods

localStorage provides two essential methods for data manipulation:

Getting Data

localStorage.getItem('key');

Setting Data

localStorage.setItem('key', 'value');

Complete Example

Let's create a button that changes its text when clicked and remembers the change using localStorage:

<!DOCTYPE html>
<html>
<head>
    <title>Button Text Change with localStorage</title>
    <style>
        #main {
            width: 200px;
            height: 50px;
            border-radius: 10px;
            font-size: 16px;
            background-color: #4CAF50;
            color: white;
            border: none;
            cursor: pointer;
        }
        #main:hover {
            background-color: #45a049;
        }
    </style>
</head>
<body>
    <h4>Click the button to change its text</h4>
    <div>
        <button id="main">CLICK ME!</button>
    </div>
    <p><small>Note: The text will persist even after page refresh!</small></p>

    <script>
        let button = document.getElementById('main');
        
        // Check if there's saved text in localStorage
        let savedText = localStorage.getItem('buttonText');
        if (savedText) {
            button.textContent = savedText;
        }
        
        // Handle button click
        button.onclick = function() {
            if (button.textContent === 'CLICK ME!') {
                button.textContent = 'CLICKED!';
                localStorage.setItem('buttonText', 'CLICKED!');
            } else {
                button.textContent = 'CLICK ME!';
                localStorage.setItem('buttonText', 'CLICK ME!');
            }
        }
    </script>
</body>
</html>

How It Works

The script follows these steps:

  • Page Load: Check localStorage for saved button text and apply it if found
  • Button Click: Toggle between "CLICK ME!" and "CLICKED!" text
  • Data Persistence: Save the current text to localStorage on each click
  • State Recovery: Restore the button's previous state when the page reloads

Advanced Example with Multiple States

Here's a more sophisticated version that cycles through multiple button states:

<!DOCTYPE html>
<html>
<head>
    <title>Multi-State Button with localStorage</title>
    <style>
        #cycleButton {
            width: 250px;
            height: 60px;
            border-radius: 15px;
            font-size: 18px;
            font-weight: bold;
            border: 2px solid #333;
            cursor: pointer;
            transition: all 0.3s ease;
        }
    </style>
</head>
<body>
    <h4>Multi-State Button Demo</h4>
    <button id="cycleButton">Start</button>
    <p id="status">Current state: 0</p>

    <script>
        let button = document.getElementById('cycleButton');
        let statusText = document.getElementById('status');
        
        let states = ['Start', 'Loading...', 'Processing', 'Complete!'];
        let colors = ['#3498db', '#f39c12', '#e74c3c', '#27ae60'];
        
        // Get saved state or default to 0
        let currentState = parseInt(localStorage.getItem('buttonState') || '0');
        
        // Initialize button
        updateButton();
        
        button.onclick = function() {
            currentState = (currentState + 1) % states.length;
            localStorage.setItem('buttonState', currentState.toString());
            updateButton();
        }
        
        function updateButton() {
            button.textContent = states[currentState];
            button.style.backgroundColor = colors[currentState];
            button.style.color = 'white';
            statusText.textContent = `Current state: ${currentState}`;
        }
    </script>
</body>
</html>

Key Benefits

  • Persistence: Button state survives browser refresh and restart
  • User Experience: Remembers user interactions across sessions
  • No Server Required: All data is stored locally in the browser
  • Fast Access: Instant retrieval of stored values

Browser Compatibility

localStorage is supported in all modern browsers including Chrome, Firefox, Safari, and Edge. It has excellent compatibility with IE8+ and all mobile browsers.

Conclusion

Using localStorage with button click events provides a powerful way to create persistent, interactive web interfaces. The combination of DOM manipulation and local storage enables rich user experiences that remember state across browser sessions.

Updated on: 2026-03-15T23:19:01+05:30

574 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements