Skip to content Skip to sidebar Skip to footer

Add To Favorites/bookmark Using Html5 Localstorage And Jquery

I want to add 'add to favorites/bookmark' feature in one of my projects, but am totally blank regarding the same. Basically, I'm using bootstrap glyphicons for user to select it if

Solution 1:

Try creating a JavaScript object and serialize it to save it in localStorage. Use something like this -

var bookmarkedItems = [];
functionItemObject(name, content)
{
   this.name = name;
   this.content = content;
}

functionaddItem()
{
  bookmarkedItems.push(newItemObject('Item1', 'Content1'));
}

functionsaveToLocalStorage(item)
{
  var ob = localStorage.get('KEY');
  if(ob)
  {
     bookmarkedItems = JSON.parse(ob);
  }
  bookmarkedItems.push(item);
  localStorage.set('KEY', JSON.stringify(bookmarkedItems);
}

OR

Refer below code -

var storageService = function () {

        varSTORAGE_KEY = "bookmarkitems";
        var bookmarkitems = {};

        var init = function () {
            bookmarkitems = sessionStorage.getItem(STORAGE_KEY);
            if (bookmarkitems) {
                bookmarkitems = JSON.parse(bookmarkitems);
            }
            else {
                bookmarkitems = {};
            }
        };

        var set = function (key, value) {
            bookmarkitems[key] = value;
            updateStorage();

        };

        var get = function (key) {
            return bookmarkitems[key];
        };

        var updateStorage = function () {
            sessionStorage.setItem(STORAGE_KEY, JSON.stringify(bookmarkitems));
        };

        return {
            init: init,
            set: set,
            get: get,
            updateStorage: updateStorage
        };
    };

Solution 2:

Here is a small example on how to use local storage:

// StorelocalStorage.setItem("lastname", "Smith");
// Retrievedocument.getElementById("result").innerHTML = localStorage.getItem("lastname");

You can reference this page for more examples. Using it is pretty simple it works like any JS Object.

EDIT: There are more extended examples on the functionality of local storage here.

Post a Comment for "Add To Favorites/bookmark Using Html5 Localstorage And Jquery"