Cookie store with toggleClass

Viewed 39

I have cookies on my site, so whenever the user clicks on 'bookmark', this will then add the class 'bookmarked' that will simply make this a different colour.

Could someone please show where I am going wrong? I want so whenever the user refreshes the page, it simply adds the class to the .bookmark class that they have previously clicked.

Also, I want that if they click the class 'bookmarked' this then removes the cookie for that. As they no longer want to book mark this.

HTML

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.1.3/js.cookie.js"></script>

<ul>
    <li><div class="bookmark">Star</div></li>
    <li><div class="bookmark">Star</div></li>
    <li><div class="bookmark">Star</div></li>   
</ul>

CSS

<style>.bookmarked {background:red;}</style>

JQuery

 <script>
 $(".bookmark").each(function () {
     if (Cookies.get($(this))) {$(this).addClass('bookmarked');}
 });

$('.bookmark').on('click', function (e) {
    e.preventDefault();
    $(this).toggleClass('bookmarked');
    Cookies.set('bookmark-' + $('.bookmark').index(this), 'bookmarked', { expires: 365 });
});
</script>
1 Answers

Firstly, note that your use of $(this) in the get() method of the cookie is incorrect. You need to use the index of the .bookmark element which can be retrieved through the first argument provided to each().

$(".bookmark").each(function(i) {
  if (Cookies.get('bookmark-' + i)) {
    $(this).addClass('bookmarked');
  }
});

$('.bookmark').on('click', function(e) {
  $(this).toggleClass('bookmarked');
  Cookies.set('bookmark-' + $(this).index('.bookmark'), 'bookmarked', {
    expires: 365
  });
});

That being said, it appears as though the cookie library you're using no longer works. In all other instances you're following the documentation they provide and no cookies are being created. Even a basic Cookies.add('foo', 'bar') does nothing.

As a workaround I would suggest you create the functionality you require using localStorage instead:

$(".bookmark").each(function(i) {
  if (localStorage.getItem('bookmark-' + i)) {
    $(this).addClass('bookmarked');
  }
});

$('.bookmark').on('click', function(e) {
  let $this = $(this).toggleClass('bookmarked');
  if ($this.hasClass('bookmarked')) {
    localStorage.setItem('bookmark-' + $this.index('.bookmark'), 'bookmarked');
  } else {
    localStorage.removeItem('bookmark-' + $this.index('.bookmark'));
  }
});

Example jsFiddle

Related