Home > Mobile >  I wrote a code to animate badge when the user click on a button, how to fix it?
I wrote a code to animate badge when the user click on a button, how to fix it?

Time:10-20

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
  });
});

CodePudding user response:

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

CodePudding user response:

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');
    }
});
  • Related