Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Feedback on my lightbox JavaScript

My JavaScript works and is Airbnb base linter compliant but I would like to know where I can improve.

I can see a particular problem with the listener event on the body within the toggleLightbox function, perhaps there is a better way to allow a user to close the modal lightbox anywhere on the body but only when the user has activated the lightbox. I have quite a few const declarations too.

const lightboxItems = document.querySelectorAll('.lightbox__item');

function toggleLightbox(event) {
  event.stopPropagation();
  event.preventDefault();

  const body = document.body;
  const thisItemSrc = event.target.style.backgroundImage.slice(4, -1);
  const thisItem = thisItemSrc.replace(/"/g, '');
  const fullView = document.createElement('div');
  const overlay = document.createElement('div');
  const viewContent = document.createElement('img');

  body.insertBefore(fullView, event.firstChild);
  body.insertBefore(overlay, body.firstChild);
  fullView.append(viewContent);
  fullView.classList.add('lighbox__item--fullview');
  overlay.classList.add('overlay');
  body.classList.add('overflow-hidden', 'pointer');
  viewContent.setAttribute('src', thisItem);

  body.addEventListener('click', () => {
    overlay.remove();
    fullView.remove();
    body.classList.remove('fixed', 'overflow-hidden', 'pointer');
  });
}


for (let i = 0; i < lightboxItems.length; i += 1) {
  const lightboxItem = lightboxItems[i];
  lightboxItem.addEventListener('click', toggleLightbox);
}

Thanks!

It appears that every time the toggleLightbox() function is called you add a new "click" listener to the body. If you throw in a "console.log('toggling')" you'll see that after two times it'll say "toggling, toggling"... then "toggling, toggling, toggling" and so on.