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:
- Reads the counter value from localStorage. If it doesn't exist, initializes it to 0.
- A paragraph element dynamically displays the counter value.
- A button is created and appended to the DOM to allow the user to increment the counter.
- The button's click event increments the counter, updates the DOM, and saves the updated value in localStorage.
1. Counter Initialization:
2. Counter Display:
3. Increment Button:
4. Event Listener:
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:
- The counter value is read from localStorage or initialized to 0 if not found.
- Dynamically created paragraph element displays the counter value.
- Increments the counter, updates the DOM, and saves the value in localStorage.
- Resets the counter to 0, updates the DOM, and saves the reset value in localStorage.
1. Counter Initialization:
2. Counter Display:
3. Increment Button:
4. Reset Button:
Live Demo:
See the Pen javascript-event-handling-exercise-16 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus.
Event Handling Exercises Previous: API Calls with Debounced Input Events in JavaScript.
Event Handling Exercises Next: Build a Shopping Cart using JavaScript and SessionStorage.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics