flinch85
flinch85

Reputation: 370

jQuery - toggle localStorage on click event

I am trying to make a favourite button that saves in local storage and you can toggle on and off.

But I am having trouble toggling local storage value on click.

This is what I have:

$(fav).click(function(){
      localStorage.setItem('favourited', 'yes');
      $(this).toggleClass('favourite');
});

I've tried using removeItem if the item is set on load but, this will just remove it once and not allow toggle.

Upvotes: 2

Views: 1659

Answers (3)

Niels Bosman
Niels Bosman

Reputation: 956

You could use conditions for the class to define wheter it's favourited or not.

$(fav).on("click", function () {
    $(this).toggleClass('favourite');
    // Define wheter its a favourite item based on the class
    let val = $(this).hasClass('favourite') ? 'yes' : 'no';
    // Set the localStorage
    localStorage.setItem('favourited', val);
});

Upvotes: 1

Sergey Mell
Sergey Mell

Reputation: 8040

I think it should be smth like this

$(fav).click(function(){

      // You should rely on the data from your local storage since user can reload your application and you cannot rely on your memory or html classes
      const fav = localStorage.getItem('favourited');

      if (fav) {
        localStorage.removeItem('favourited');
        $(this).removeClass('favourite');
      } else {
        localStorage.setItem('favourited', 'yes');
        $(this).addClass('favourite');
     }
});

Upvotes: 1

Ankita Kuchhadiya
Ankita Kuchhadiya

Reputation: 1282

You can use the hasClass() method to check the class exist or not then toggle the localStorage according to that:

$(fav).click(function() {
  // if there is a class we set "No" to local storage
  // because the code for toggle will remove that class from the HTML
  var value = $(this).hasClass('favourite') ? 'No' : 'yes';
  localStorage.setItem('favourited', value);
  $(this).toggleClass('favourite');
});

Illustration

var fav = $('.btn');
$(fav).click(function() {
  // if there is a class we set "No" to local storage because the code for toggle will remove that class from the HTML
  var value = $(this).hasClass('favourite') ? 'No' : 'yes';
  console.log(value);
  $(this).toggleClass('favourite');
});
.favourite {
  color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button class="btn">Click</button>

Upvotes: 1

Related Questions