So I have a very simple code that retrieves the text content of a dynamically updated <h1> element and saves that to localStorage as a "bookmark" for later use. I want to have the feature which saves and deletes the bookmark from localStorage upon the click of a button from the user. Here's a very layman code of what I'm trying to get at here.
function myFunc() {
//Get place name and store it to place var
var place = document.getElementById("place").innerHTML
//Switch button to display save/delete bookmark
var button = document.getElementById("button")
if (button.innerHTML == "Delete") {
button.innerHTML = "Save"
//code runs when "delete" is pressed
var bookmarks = localStorage.getItem("bookmarks")
//convert bookmarks into array by using .split
bookmarks = bookmarks.split(", ")
//remove last item using bookmarks.pop()
bookmarks.pop()
// set into localStorage
localStorage.setItem("bookmarks", bookmarks)
console.log(bookmarks)
console.log("deleted")
} else {
//code runs when "save" button is clicked
button.innerHTML = "Delete"
//check if localStorage is empty
var bookmarks = localStorage.getItem("bookmarks")
if(bookmarks === null) {
//if localStorage "bookmarks" has nothing, save place name in it
localStorage.setItem("bookmarks", place)
} else {
//if localStorage "bookmarks" has something, push place name into the array
var array = []
array.push(bookmarks)
array.push(place)
// set updated array into localStorage "bookmarks"
localStorage.setItem("bookmarks", array)
console.log(bookmarks)
console.log("saved")
}
}
}
<h1 id="place">
Atlanta, Georgia
</h1>
<button id="button" onclick="myFunc()">
Save
</button>
In my mind, the final outcome should look like this:
once save is pressed, the console displays ["Atlanta, Georgia"] and "Atlanta, Georgia" is saved into localStorage.
Once delete is clicked, the console removes "Atlanta, Georgia" from the localStorage.