JSFiddle - React, Tailwind, and code Playground

by Kriti

HTML

<button id="addButton">Add Book</button>
<br>
<br>
<input type="search" id="search">
<button id="remButton">Remove Book</button>
<br>
<br>
<div id="storedBooks"></div>

JavaScript

// basic app to store timestamp in local storage

// Click "Add to Storage" to add a book to the #stored element
// Click "Remove from Storage" to remove the last element from localStorage and the #stored element

//localStorage.clear(); //run this to clear localStorage
var totalItems = localStorage.length,
    stored = document.getElementById('storedBooks'),
    addBooks = document.getElementById('addButton'),
    remBooks = document.getElementById('remButton');

addBooks.addEventListener('click', addToStorage);
remBooks.addEventListener('click', removeStorage);

updateStorage(); // adds stored timestamps to #stored div

function updateStorage() {
    // Reset/update innerHTML for #stored div
    stored.innerHTML = "Books in the List: <br>"

    for (item in localStorage) {
        var obj = JSON.parse(localStorage[item]);
        stored.innerHTML += obj.time + '<br>';
    }
}

function addToStorage(event) {
    // Create a new localStorage property and assign its value
    var propName = 'item' + totalItems;
    localStorage.setItem(propName, JSON.stringify({
        'time': (event.timeStamp).toString(),
            'target': (event.target).toString()
    }));
    totalItems = localStorage.length;

    // Add new value to #stored element
    var obj = JSON.parse(localStorage[propName]);
    stored.innerHTML += obj.time + '<br>';
}

function removeStorage() {
    // Remove the latest property from localStorage
    var propName = 'item' + (totalItems - 1);
    localStorage.removeItem(propName);
    totalItems = localStorage.length;

    // Update html to reflect changes
    updateStorage();
}