skip to Main Content

I wrote this

hover the animation: animated slideIn doesn’t trigger, while the console show notihing

let getAddToCart = document.querySelectorAll('.addToCart');
let getCartBadge = document.querySelector('.cartBadge');

getAddToCart.forEach((item) => {
  item.addEventListener('click', function (e) {
    e.preventDefault();

    console.log('clicked');

    // animate the cartBadge
    getCartBadge.classList.add('animated', 'slideIn');

    // other stuff
  });
});

2

Answers


  1. You can’t add a class name with space in it. Try adding them with two statements, or use animated-slideIn.

    Login or Signup to reply.
  2. This is a guess: You checked the scope inside your event listener? Try select getCartBadge using a variable self in external scope:

    let getAddToCart = document.querySelectorAll('.addToCart');
    let getCartBadge = document.querySelector('.cartBadge');
    let self = this;
    
    getAddToCart.forEach((item) => {
      item.addEventListener('click', function (e) {
        e.preventDefault();
        self.getCartBadge.classList.add('animated', 'slideIn');
      });
    });
    

    or using arrow function:

    let getAddToCart = document.querySelectorAll('.addToCart');
    let getCartBadge = document.querySelector('.cartBadge');
    
    getAddToCart.forEach((item) => {
      item.addEventListener('click', (e) => {
        e.preventDefault();
        getCartBadge.classList.add('animated', 'slideIn');
      });
    });
    

    See more about scopes in:
    https://www.programiz.com/javascript/variable-scope
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions


    Shortened version if you want to explore:

    const getAddToCart = document.querySelectorAll('.addToCart');
    const getCartBadge = document.querySelector('.cartBadge');
    
    getAddToCart.forEach(item => {
        item.onclick = (event) => {
            event.preventDefault();
            getCartBadge.classList.add('animated', 'slideIn');
        }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search