jcho0627
1/23/2019 - 7:03 AM

[JS] Event Listener and Set Local Storage

// Listen for Form Submit
document.getElementById('myForm').addEventListener('submit', saveBookmark);

// Save Bookmark
function saveBookmark(e) {
    // Get form values
    var siteName = document.getElementById('siteName').value;
    var siteUrl = document.getElementById('siteUrl').value;

    var bookmark = {
        name: siteName,
        url: siteUrl
    }

    // Check if bookmarks is null
    if (localStorage.getItem('bookmarks') === null) {
      // Initiate Array
      var bookmarks = [];
      // Add bookmark in Array
      bookmarks.push(bookmark);
      // Set to local storage
      localStorage.setItem('bookmarks', JSON.stringify(bookmarks));
    } else {
      //Get bookmarks from Local Storage
      var bookmarks = JSON.parse(localStorage.getItem('bookmarks'));
      // Add bookmark in Array
      bookmarks.push(bookmark);
      // Re-set to local Storage
      localStorage.setItem('bookmarks', JSON.stringify(bookmarks));
    }
}