window.Wishlist = {
storageKey: 'em_wishlist',
getItems: function() {
try { return JSON.parse(localStorage.getItem(this.storageKey)) || []; }
catch(e) { return []; }
},
saveItems: function(items) {
localStorage.setItem(this.storageKey, JSON.stringify(items));
document.dispatchEvent(new CustomEvent('wishlist:updated', { detail: items }));
},
add: function(product) {
var items = this.getItems();
if (!items.find(function(i){ return i.id === product.id; })) {
items.push(product);
this.saveItems(items);
}
},
remove: function(id) {
var items = this.getItems().filter(function(i){ return i.id !== id; });
this.saveItems(items);
},
has: function(id) {
return !!this.getItems().find(function(i){ return i.id === id; });
},
count: function() { return this.getItems().length; },
clear: function() { this.saveItems([]); }
};
document.addEventListener('DOMContentLoaded', function() {
document.querySelectorAll('[data-wishlist-add]').forEach(function(btn) {
var id = btn.getAttribute('data-wishlist-add');
if (window.Wishlist.has(id)) btn.classList.add('in-wishlist');
btn.addEventListener('click', function(e) {
e.preventDefault();
var product = {
id: btn.getAttribute('data-wishlist-add'),
title: btn.getAttribute('data-title'),
price: btn.getAttribute('data-price'),
image: btn.getAttribute('data-image'),
url: btn.getAttribute('data-url'),
brand: btn.getAttribute('data-brand') || ''
};
if (window.Wishlist.has(product.id)) {
window.Wishlist.remove(product.id);
btn.classList.remove('in-wishlist');
} else {
window.Wishlist.add(product);
btn.classList.add('in-wishlist');
}
updateWishlistCount();
});
});
updateWishlistCount();
});
function updateWishlistCount() {
var count = window.Wishlist.count();
document.querySelectorAll('[data-wishlist-count]').forEach(function(el) {
el.textContent = count;
el.style.display = count > 0 ? 'inline-flex' : 'none';
});
}
document.addEventListener('wishlist:updated', updateWishlistCount);
♡ Wishlist