Sorry guys I need help. I want to make a wish list toggle were clicking on the icon - fa-heart changes from outline to solid. I have achieved that. My problem is, that the tooltip (add to wish list) should change on the target element to "added to wish list". But instead, it is changing on all elements of the array. How can I stop this behavior to make it change only on the target element? Thanks.
let i, j, toolTip;
let addItem;
for (i = 0; i < addToWish.length; i ) {
let addItem = addToWish[i];
function addToWishList() {
addItem.classList.add('fas');
addItem.classList.add('far');
favIconData ;
favDataOutput.textContent = favIconData;
navActionBadge.setAttribute('value', `${favIconData}`);
if (favIconData >= 1) {
favoriteIcon.classList.add('fas');
favoriteIcon.classList.remove('far');
} else {
favoriteIcon.classList.remove('fas')
favoriteIcon.classList.add('far')
}
}
function removeWishList() {
addItem.classList.remove('fas');
addItem.classList.add('far');
favIconData--;
favDataOutput.textContent = favIconData;
navActionBadge.setAttribute('value', `${favIconData}`);
if (favIconData >= 1) {
favoriteIcon.classList.add('fas');
favoriteIcon.classList.remove('far');
} else {
favoriteIcon.classList.remove('fas')
favoriteIcon.classList.add('far')
}
}
addItem.addEventListener('click', () => {
if (addItem.classList.contains('fas')) {
for (let j = 0; j < cardLabel.length; j ) {
let label = cardLabel[j];
label.textContent = 'Add to wishlist';
}
removeWishList()
} else {
for (let j = 0; j < cardLabel.length; j ) {
let label = cardLabel[j];
label.textContent = 'Added to wishlist';
}
addToWishList()
}
})
}
<html>
<li >
<button aria-labelledby="card-label-2">
<i id="fav" >.</i>
</button>
<div id="card-label-3">Add to Wishlist</div>
</li>
</html>
CodePudding user response:
Don't use a loop to update all the labels. Just change the label after the current button.
addItem.addEventListener('click', () => {
let label = addItem.closest(".card-action-item").querySelector(".card-action-tooltip");
if (addItem.classList.contains('fas')) {
label.textContent = 'Add to wishlist';
removeWishList()
} else {
label.textContent = 'Added to wishlist';
addToWishList()
}
})