Martz89
Martz89

Reputation: 67

Event listener on multiple elements with the same class

On the site I have a navbar. When I click on the a in navbar I want a new div (with content) appears and everything else "hides". I did it withdisplay: none. In the corner there should be an "X" which closes the div and makes "first screen" appear again.

I did the first part, but have some problems with closing. Here is my code:

const about = document.getElementById('li-about');
const work = document.getElementById('li-work');
const contact = document.getElementById('li-contact');

^These are links in a navbar.

const openSlide = (id) => {
document.querySelector('main article#' + id).style.display = 'block';
document.querySelector('header').style.display = 'none';
};

about.addEventListener('click', () => openSlide('about'));
work.addEventListener('click', () => openSlide('work'));
contact.addEventListener('click', () => openSlide('contact'));

And here is the code. It works. But when I want to do similar thing to a closing div function, it only works with about, not work and contact.

const closeSlide = (id) => {
document.querySelector('main article#' + id).style.display = 'none';
document.querySelector('header').style.display = 'block';
};

const close = document.querySelector('.close');
close.addEventListener('click', () => closeSlide('about'));
close.addEventListener('click', () => closeSlide('work'));
close.addEventListener('click', () => closeSlide('contact'));

Can you tell me why? There is no error in console, I tried to replace closeSlide function with a simple console.log and it doesn't work as well. Is it possible that JavaScript detects only one (first in HTML code) .close div?

Upvotes: 2

Views: 3960

Answers (1)

AuxTaco
AuxTaco

Reputation: 5171

Is it possible that JavaScript detects only one (first in HTML code) .close div?

Yes, document.querySelector returns the first matching element it finds in the DOM. If you want to add your listeners to every .close on the page, either loop through the NodeList returned by document.querySelectorAll:

const closeList = document.querySelectorAll('.close');
closeList.forEach(element => {
  element.addEventListener('click', () => closeSlide('about'));
  element.addEventListener('click', () => closeSlide('work'));
  element.addEventListener('click', () => closeSlide('contact'));
};

or add a listener to an element containing all of your .close elements that only takes action if a .close was clicked:

document.querySelector('#some-container').addEventListener('click', evt => {
  if (!evt.target.closest('.close')) return;
  closeSlide('about');
  closeSlide('work');
  closeSlide('contact');
});

Upvotes: 5

Related Questions