0

I would like the selected element to be remembered by the browser. It's my first time to use js-cookie and I find the documentation very lacking. My inexperience doesn't help either so I decided to ask for some help here.

HTML

   <ul>
      <li class='selected' id='item1'>
        <img src='https://dummyimage.com/100x100/000/fff'/>
      </li>

      <li id='item2'>
        <img src='https://dummyimage.com/100x100/000/fff'/>
      </li>

      <li id='item3'>
        <img src='https://dummyimage.com/100x100/000/fff'/>
      </li>
    </ul>

CSS

ul{margin:0;padding:0}
li{float:left;list-style-type:none}
img{margin-left:5px}
.selected img{border:3px solid red}

Script

$('li').on('click', function(){
    $(this).siblings().removeClass('selected')
    $(this).addClass('selected');
})

Here's the JsFiddle of what I'm trying to accomplish. https://jsfiddle.net/cb7pf26u/3/

Vianne
  • 506
  • 1
  • 8
  • 26

1 Answers1

0

For data you want to keep locally and do not need to pass to the server it's better to keep it in localstorage vs a cooke. cookies get passed back to the server ever request and no need to waste resources.

here's a fiddle for you - https://jsfiddle.net/denov/cb7pf26u/4/

function setStyle(node) {
    node.siblings().removeClass('selected')
    node.addClass('selected');
}

function startup() {
    var defaultId = 'item1';
        lastId = localStorage.getItem('keep_track_example') || defaultId;            

    $('li').on('click', function(){
        setStyle($(this));
        localStorage.setItem('keep_track_example', $(this).attr('id'));
    })

    setStyle($('#'+lastId));    
}


startup();

if you really wanted to use a cookie you just need to replace the calls to localstorage with $.cookie()

denov
  • 7,064
  • 2
  • 23
  • 36