HendrikEng
HendrikEng

Reputation: 684

Passing an argument to a function inside a forEach.call

i am trying to understand how i would pass an argument to a function inside a forEach.call. I basically converted my code into an object literal and split up the functions to be more dry when i would later add more animations.

The problem is, that it logs the element on load but not anymore after that, i guess its because the variable doesn't exist after the first log anymore. how would i make it work, or is the approach completely wrong and nonsense?

working example: https://codepen.io/HendrikEng/pen/aEKPmM?editors=1010

my failing dry attempt: https://codepen.io/HendrikEng/pen/XVBpPV?editors=0011

const who = {
  trigger: [...document.getElementsByClassName('slide')],

  init: () => {
    console.log('init');
    who.trigger.forEach.call(who.trigger, (el) => {
      el.addEventListener('mouseover', who.animateOver(el), false);
    });
    who.trigger.forEach.call(who.trigger, (el) => {
      el.addEventListener('mouseout', who.animateOut(el), false);
    });
  },

  animateOver: (el) => {
    console.log('animateOver');
    console.log(el);
    // animate image
    const image = el.getElementsByClassName("img")[0];

    TweenMax.to(image, 0.25, {
      yPercent: 35,
      ease: Power1.easeOut,
    });
  },

  animateOut: (el) => {
    console.log(el);
    console.log('animateOut');
    const image = el.getElementsByClassName('img')[0];
    TweenMax.to(image, 0.75, {
      yPercent: 0,
      ease: Bounce.easeOut,
    });
  },

  debug: () => {
    console.log('debug');
  },

  destroy() {
    console.log('destroy');
  },
};

who.init();

Upvotes: 1

Views: 49

Answers (1)

guest271314
guest271314

Reputation: 1

The code at Question calls the functions set at .addEventListener() instead of referencing the function to call when the event is dispatched. Also, the event is attached to the <img> element, .getElementsByClassName() call is not necessary

const who = {
  trigger: [...document.getElementsByClassName('slide')],

  init: () => {
    console.log('init');
    who.trigger.forEach.call(who.trigger, (el) => {
      el.addEventListener('mouseover', who.animateOver, false);
    });
    who.trigger.forEach.call(who.trigger, (el) => {
      el.addEventListener('mouseout', who.animateOut, false);
    });
  },

  animateOver: (el) => {
    console.log('animateOver');
    console.log(el);
    // animate image
    const image = el.target;
    console.log(image);
    TweenMax.to(image, 0.25, {
      transformStyle: 'preserve-3d',
      yPercent: 35,
      ease: Power1.easeOut,
    });
  },

  animateOut: (el) => {
    console.log(el);
    console.log('animateOut');
    const image = el.target;
    TweenMax.to(image, 0.75, {
      yPercent: 0,
      ease: Bounce.easeOut,
    });
  },

  debug: () => {
    console.log('debug');
  },

  destroy() {
    console.log('destroy');
  },
};

onload = () => who.init();

Upvotes: 2

Related Questions