I'm creating a simple add to cart feature using jQuery and localStorage. Everything works fine, but I cannot add a selected class to the Add to Cart button. Please help me to add and remove (toggle) the selected class.
I need the logic to set the class on the buttons based on whether or not the product is held in the JSON I am holding in localStorage.
var favorites = JSON.parse(localStorage.getItem('favorites')) || [];
var list = $("#fav-list");
var parent = list.parent();
function addFavList() {
list.detach().empty().each(function(i) {
for (var x = 0; x < favorites.length; x++) {
$(this).append('<li>' + favorites[x] + '</li>');
if (x == favorites.length - 1) {
$(this).appendTo(parent);
}
}
});
}
addFavList();
$(document).delegate('.cart', 'click', function(e) {
var id = $(this).parent().html(),
index = favorites.indexOf(id);
if (!id)
return;
if (index == -1) {
favorites.push(id);
} else {
favorites.splice(index, 1);
$(this).parent().removeClass('fav');
}
localStorage.setItem('favorites', JSON.stringify(favorites));
addFavList();
});
$(document).delegate('#delete', 'click', function() {
localStorage.clear();
location.reload();
});
Please check this Fiddle where I have tried my best
from localStorage Add to Cart
No comments:
Post a Comment