// wishList function
function wishListSt() {
let wishlistItems = JSON.parse(sessionStorage.getItem('wishlistItems')) || [];
let cardBtns = document.querySelectorAll('.wishlist_btn_st');
let cardBox = document.querySelector('.wishlist_new_box');
// add wishlist items from sessionStorage
function addWishlistItems() {
// Add to wishlist
for (let i = 0; i < cardBtns.length; i++) {
cardBtns[i].addEventListener('click', () => {
if (cardBtns[i].classList.contains('btn_added_to_wishlist')) {
alert('Товар уже добавлен в избранное');
} else {
let item = cardBtns[i].parentElement;
cardBtns[i].classList.remove('wishlist_btn_st');
cardBtns[i].classList.add('btn_added_to_wishlist');
let clone = item.cloneNode(true);
cardBox.appendChild(clone);
// Add the item to the wishlistItems array
wishlistItems.push(clone.innerHTML);
// Store the updated wishlistItems in sessionStorage
sessionStorage.setItem('wishlistItems', JSON.stringify(wishlistItems));
}
});
}
}
addWishlistItems();
// Load wishlist items from sessionStorage
function loadWishlistItems() {
for (let i = 0; i < wishlistItems.length; i++) {
let item = document.createElement('li');
item.className = "pif-has-gallery product type-product";
item.innerHTML = wishlistItems[i];
cardBox.appendChild(item);
}
// Add class to buttons of products already in wishlist
let wishlistButtons = document.querySelectorAll('.wishlist_btn_st');
for (let i = 0; i < wishlistButtons.length; i++) {
let item = wishlistButtons[i].parentElement;
if (wishlistItems.includes(item.innerHTML)) {
wishlistButtons[i].classList.add('btn_added_to_wishlist');
}
}
}
loadWishlistItems();
// Remove from wishlist
let wishlistBtnHeader = document.querySelector('.wishlist_btn_in_header')
function removeFromWishlist() {
console.log('555');
let cardBoxItems = document.querySelectorAll('.wishlist_new_box .product');
for (let i = 0; i < cardBoxItems.length; i++) {
let btnRemove = cardBoxItems[i].querySelector('.btn_added_to_wishlist');
if (btnRemove) {
btnRemove.addEventListener('click', () => {
// Find the index of the item in the wishlistItems array
let itemIndex = wishlistItems.findIndex(item => item === cardBoxItems[i].innerHTML);
// Remove the item from the wishlistItems array
if (itemIndex !== -1) {
wishlistItems.splice(itemIndex, 1);
}
// Update the stored wishlistItems in sessionStorage
sessionStorage.setItem('wishlistItems', JSON.stringify(wishlistItems));
cardBoxItems[i].remove();
// Reassign the event listener to the updated button elements
removeFromWishlist();
});
}
}
}
wishlistBtnHeader.addEventListener('click', () => {
removeFromWishlist();
})
}
document.addEventListener('DOMContentLoaded', function() {
wishListSt();
});