w3resource

Creating a Persistent Counter with JavaScript and LocalStorage

JavaScript Event Handling: Exercise-16 with Solution

LocalStorage Counter

Write a JavaScript program that implements a counter using localStorage to save the count across page refreshes.

Solution 1: Basic Counter with Increment Button

JavaScript Code:

// Initialize the counter from localStorage or set it to 0 if not found
let counter = parseInt(localStorage.getItem('counter')) || 0;

// Create a display element to show the counter value
const counterDisplay = document.createElement('p');
counterDisplay.id = 'counterDisplay';
counterDisplay.textContent = `Counter: ${counter}`;
document.body.appendChild(counterDisplay); // Add the display to the DOM

// Create an increment button
const incrementButton = document.createElement('button');
incrementButton.textContent = 'Increment';
document.body.appendChild(incrementButton); // Add the button to the DOM

// Add click event to the increment button
incrementButton.addEventListener('click', () => {
  counter++; // Increment the counter
  localStorage.setItem('counter', counter); // Save the counter value to localStorage
  counterDisplay.textContent = `Counter: ${counter}`; // Update the display
});

Output:

Counter: 3

Increment

Explanation:

    1. Counter Initialization:

    • Reads the counter value from localStorage. If it doesn't exist, initializes it to 0.

    2. Counter Display:

    • A paragraph element dynamically displays the counter value.

    3. Increment Button:

    • A button is created and appended to the DOM to allow the user to increment the counter.

    4. Event Listener:

    • The button's click event increments the counter, updates the DOM, and saves the updated value in localStorage.

Solution 2: Counter with Increment and Reset

JavaScript Code:


// Initialize the counter from localStorage or set it to 0 if not found
let counter = parseInt(localStorage.getItem('counter')) || 0;

// Create a display element to show the counter value
const counterDisplay = document.createElement('p');
counterDisplay.id = 'counterDisplay';
counterDisplay.textContent = `Counter: ${counter}`;
document.body.appendChild(counterDisplay); // Add the display to the DOM

// Create an increment button
const incrementButton = document.createElement('button');
incrementButton.textContent = 'Increment';
document.body.appendChild(incrementButton); // Add the button to the DOM

// Create a reset button
const resetButton = document.createElement('button');
resetButton.textContent = 'Reset';
document.body.appendChild(resetButton); // Add the reset button to the DOM

// Add click event to the increment button
incrementButton.addEventListener('click', () => {
  counter++; // Increment the counter
  localStorage.setItem('counter', counter); // Save the counter value to localStorage
  counterDisplay.textContent = `Counter: ${counter}`; // Update the display
});

// Add click event to the reset button
resetButton.addEventListener('click', () => {
  counter = 0; // Reset the counter
  localStorage.setItem('counter', counter); // Save the reset value to localStorage
  counterDisplay.textContent = `Counter: ${counter}`; // Update the display
});

Output:

Counter: 2
Increment  Reset

Explanation:

    1. Counter Initialization:

    • The counter value is read from localStorage or initialized to 0 if not found.

    2. Counter Display:

    • Dynamically created paragraph element displays the counter value.

    3. Increment Button:

    • Increments the counter, updates the DOM, and saves the value in localStorage.

    4. Reset Button:

    • Resets the counter to 0, updates the DOM, and saves the reset value in localStorage.

Live Demo:

See the Pen javascript-event-handling-exercise-16 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript program that implements a counter using localStorage, updating the count with each button click.
  • Write a JavaScript function that increments a stored counter in localStorage and displays the new value dynamically.
  • Write a JavaScript program that maintains multiple counters in localStorage and updates them based on user interaction.
  • Write a JavaScript function that resets a localStorage counter when a designated reset button is clicked.

Go to:


PREV : Debounce Input Event.
NEXT : SessionStorage Cart.

Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.