Search code examples
javascriptcookiessession-storage

How to reload current page and remember toggled class


Im reading in a flickr api list, and dynamically outputting into an unordered list format using some standard javascript. I have added functionality which enables you to toggle 'selected' class to the list.

How can i add cookie to the code which helps remember which list items i have selected when refreshing the page?

http://codepen.io/coolkingkhan/pen/PZvPOB

only pure javascript please IE8+

****** Javascript code *******

(function () {

  var tags = 'london',
    label = 'Small 320',
script = document.createElement( 'script' );

    script.src ='http://api.flickr.com/services/feeds/photos_public.gne?format=json&jsoncallback=cb&tags=' + tags + '&label=' + label;
    document.head.appendChild(script);

})();

function cb(data) {
  // output the flickr images from api into img element within an unordered list
  var output='<ul>';
  for (var i=0; i < 9; i++) { 
    var imgURL = data.items[i].media.m;
    output+='<li class="flickrlistitem">' + '<img src=' + imgURL + '/>' + '</li>';
  }
  output+='</ul>';
  document.getElementById('flickrfeed').innerHTML = output;

  // add click event on all items with the classname flickrlistitem
  var anchor = document.querySelectorAll('.flickrlistitem');                
    for (var i=0; i < anchor.length; i++){
        anchor[i].addEventListener("click", function(){
          this.classList.toggle('selected');
        }, false);
    }   
}

****** HTML code *******

<div class="main-container">
  <div id="flickrfeed">
  </div>
</div>

Solution

  • There was a similar question to this one a few minutes ago: location.reload(), Javascript,HTML

    Basically when the page reloads they set a cookie to read it later.... This approach should work.