Set and get cookie array of added html elements for each page/url

I have a bookmark function that appends a caret (element) to a progress bar (element). The caret is absolutely positioned relative to the progress bar's width. The user can add multiple bookmarks. Resultant HTML;

<div class="progress-bar" style="width: 50%;">
    <div class="caret" style=" left:50%;"></div>
    <div class="caret" style=" left:60%;"></div>
</div>

What I would like to do is save these bookmarks in a cookie so that when the user revisits the page the bookmarks are in place.

I have the basic setup using this solution how to store an array in jquery cookie?

But I am stuck as to how to store and show a set of saved bookmark elements and how to do this for each page / url where bookmarks are saved.

Fiddle https://jsfiddle.net/jabuka/spevhqxv/

Thank you.

Answers 1

  • Add each element you create to an array, then convert it to a JSON object and store it in local storage, like this:

    var json = JSON.stringify(elems);
    localStorage.setItem('bookmarks', json);
    

    When the user revisits the page you can load the JSON page again and add the elements:

    elems = JSON.parse(localStorage.getItem('bookmarks'));
    for(var i in elems){
     $('.progress-bar').append(elems[i]);
    }
    

    Here is a working JSFiddle


Related Articles