Skip to content

Instantly share code, notes, and snippets.

@vxhviet
Last active July 25, 2023 11:42
Show Gist options
  • Save vxhviet/0699ff07511b016d489add9f9c2e5b42 to your computer and use it in GitHub Desktop.
Save vxhviet/0699ff07511b016d489add9f9c2e5b42 to your computer and use it in GitHub Desktop.

[JavaScript] - Passing Arguments to Event Handlers

SOURCE

<nav class="nav">
        <img
          src="img/logo.png"
          alt="Bankist logo"
          class="nav__logo"
          id="logo"
          designer="Jonas"
          data-version-number="3.0"
        />
        <ul class="nav__links">
          <li class="nav__item">
            <a class="nav__link" href="#section--1">Features</a>
          </li>
          <li class="nav__item">
            <a class="nav__link" href="#section--2">Operations</a>
          </li>
          <li class="nav__item">
            <a class="nav__link" href="#section--3">Testimonials</a>
          </li>
          <li class="nav__item">
            <a class="nav__link nav__link--btn btn--show-modal" href="#"
              >Open account</a
            >
          </li>
        </ul>
      </nav>
// Menu fade animation, fade out on mouse over
const nav = document.querySelector('.nav');

/* const handleHover = function (e, opacity) {
  if (e.target.classList.contains('nav__link')) {
    const link = e.target;
    const siblings = link.closest('.nav').querySelectorAll('.nav__link');
    const logo = link.closest('.nav').querySelector('img');

    siblings.forEach(el => {
      if (el !== link) el.style.opacity = opacity;
    });
    logo.style.opacity = opacity;
  }
}; */

// these don't work as we need to pass a function into the second param of addEventListener()
// instead of invoking a function
// nav.addEventListener('mouseover', handleHover(e, 0.5));
// nav.addEventListener('mouseout', handleHover(e, 1));

// one solution
/* nav.addEventListener('mouseover', function (e) {
  handleHover(e, 0.5);
}); */

// but we can do better with bind() method
const handleHover = function (e) {
  if (e.target.classList.contains('nav__link')) {
    const link = e.target;
    const siblings = link.closest('.nav').querySelectorAll('.nav__link');
    const logo = link.closest('.nav').querySelector('img');

    siblings.forEach(el => {
      if (el !== link) el.style.opacity = this; // this has now been changed to opacity
    });
    logo.style.opacity = this;
  }
};

// passing "arguments" into handlers
nav.addEventListener('mouseover', handleHover.bind(0.5));
nav.addEventListener('mouseout', handleHover.bind(1));

// Handler function can only have one real argument (`function (e)` in this case).
// If we want to pass additional argument into this function, we use `this` like
// we did here. If we want to pass multiple values, then we can pass in an array
// or an object into `bind()`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment