When clicking on an item in the wishlist, only the text for that specific item should change,

Hi all, I'm in need of some assistance. I have successfully created a wishlist toggle where clicking on the heart icon changes it from an outline to solid. However, my issue lies in changing the tooltip text from "add to wish list" to "added to wish list" only on the target element, instead of changing it on all elements in the array. How can I prevent this behavior and make the tooltip change only on the target element? Thank you for your help.

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 class="card-action-item">
  <button class="card-action-btn" aria-labelledby="card-label-2">
    <i id="fav"  class="far fa-heart">.</i>
  </button>
  <div class="card-action-tooltip" id="card-label-3">Add to Wishlist</div>
</li>

</html>

Answer №1

A more efficient way to update labels is by directly changing the label associated with 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 cart';
      removeCart()
    } else {
      label.textContent = 'Added to cart';
      addToCart()
    }
  })

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble with string matching in JavaScript?

My attempts to verify my Ajax response with a string have consistently resulted in a fail case being printed. Below is the section of code relating to my ajax request: var username = document.getElementById("name").value; var password = document.getEle ...

Some CSS features might not work properly when using Vuetify alongside Vue.js and Webpack

I believe the issue may stem from my inability to correctly import the JS file for Vuetify, but I haven't been able to pinpoint any errors. It seems that certain CSS functionalities of Vuetify, like list highlight events, are not working in my applica ...

SmartEdit functions properly when spartacus is running using yarn start --ssl, but does not work without SSL enabled

I followed the smartedit setup instructions at and everything works well when I start the Spartacus server with yarn start --ssl. However, if I start the server with just yarn start, the storefront does not appear. See image here for reference ...

Does ng-include fetch the included HTML files individually or merge them into a single HTML file before serving?

Is there a performance impact when using the ng-include Angular directive, in terms of having included HTML files downloaded as separate entities to the user's browsers? I am utilizing a CDN like AWS CloudFront instead of a node server to serve the H ...

What is the functionality of this JQuery Popup?

I'm facing an issue with my JQuery Popup. When the "Login" button is clicked, it hides the Login popup but doesn't show the Sign Up popup. How can I make sure that clicking on "Login" hides the Login popup and shows the Sign Up popup accordingly? ...

Tips for setting up a full-size image with nextJS and the <Image /> component

Upgrading NextJS to the latest version has resulted in some errors when using the Image component: // import Image from 'next/image' <div style={Object.assign({}, styles.slide, style)} key={key}> <Image src={src} alt="&quo ...

I am looking to modify the background color of characters in a text box once the characters in a textarea exceed 150 characters

Currently, I am utilizing event.data to capture the text inputted into this particular HTML textbox. My intention is to change the background color to red based on that input. However, when using the style attribute on event.data, I encounter an error. It& ...

Determine if an element from the first array is present in the second array

I've encountered a challenge while building a simple react app and I could use some help. The Problem at Hand :- My goal is to compare items in firstArray (which contains separate dictionaries) with those in secondArray. While the loop for checking ...

Method for creating a randomized layout grid in MaterialUI where each row contains a total of three columns

In the process of developing a React application that interacts with the reddit api and oAuth. Utilizing MaterialUI, I am currently experimenting with the Component to create a 3 column grid of images with dynamically generated column widths, maxing out a ...

Using [(ngModel)] in Angular does not capture changes made to input values by JavaScript

I have developed a custom input called formControl, which requires me to fetch and set its value using [(ngModel)]: import { Component, Injector, OnInit, forwardRef } from '@angular/core'; import { ControlValueAccessor, FormControl, NG_VALUE_ACCE ...

Instructions for including dependencies from a globally installed npm package into a local package

I've noticed that although I have installed a few npm packages globally, none of them are showing up in any of my package.json files. What is the recommended npm command to automatically add these dependencies to all of my package.json files? ...

Unable to resolve an unresolved issue with a jquery or javascript bug

I am currently facing some issues with my jQuery code in both Firebug and Chrome's developer tools. Any assistance would be greatly appreciated. Kindly make the necessary updates in the provided fiddle. Please follow this link to access the fiddle: ...

CSS - Discovering the reason behind the movement of text post generation (animation)

I have a question regarding CSS animation, specifically the typewriting effect. I was able to successfully achieve the typewriting effect using animation. However, I noticed that even though I did not set any animation for transforming, once the text is g ...

Getting AJAX parameters from Angular in Node/Express Js

I am encountering an issue with my factory, which sends an ajax userId call to my node server. usersModel.getUser = function(userId){ return $http({ method: 'GET', url: 'http://localhost:3000/users/details', ...

Utilizing AJAX for XML data parsing

I need help with formatting XML data into a table. The code I've written isn't working as expected. The XML data is structured in branches, causing it to not display correctly. Can someone assist me in fixing this issue? <!DOCTYPE html> &l ...

Error 404 in Angular HTTP Request

I'm encountering a 404 error while attempting to send a post request, along with a 'possibly unhandled rejection' error. Given my limited experience with Angular, any advice would be greatly appreciated. I've gone through the documentat ...

Error in NodeJS when trying to run ESM: "ReferenceError: exports is not defined

Having a tough time with this task. I'm attempting to execute ESM scripts on Node 14 (AWS Lambda) I am working on running this piece of code to convert 3D objects to THREE JSON. This involves using the command node -r esm fbx2three.js model.fbx. I ...

Client-side validation with Jquery is failing to function properly

Currently, I am experimenting with the jquery.validate.unobtrusive.js plugin to dynamically generate form fields. Here is an example of how I'm creating a textarea field: var message = $("<textarea id='test'></textarea>"); $(mes ...

What are the steps to incorporate ThreeJS' FontLoader in a Vue project?

I am encountering an issue while attempting to generate text in three.js using a font loader. Despite my efforts, I am facing difficulties in loading the font file. What could be causing this problem? const loader = new FontLoader(); loader.load( ' ...

Is it possible to embed a Microsoft Teams meeting within an Iframe?

Is it possible for MS Teams to provide a URL of a video meeting that can be embedded in external locations, such as an iframe on my website? I attempted to add it like this: <iframe src="https://teams.microsoft.com/l/meetup-join/19%3ameeting_N2E3M ...