Skip to content
Advertisement

Click Event Shows And Removes All Overlays Instead Of Individually – JavaScript

I have a wrapper container where I would like is so when I click on the name each piece of info shows just for that wrapper and when I click/close the ‘x’ button it only removes it for that button.

Using the forEach() method it is showing and removing all of the inner containers except for just the ones that have been clicked.

I thought it might be possible doing with the this keyword but I couldn’t get it to work.

I’m new to Javascript so any help would be hugely appreciated.

Codepen: https://codepen.io/anna_paul/pen/JjWPLjx

JavaScript
JavaScript
JavaScript

Advertisement

Answer

You’ve pretty much identified the issue in your question which is that you are looping over all the panels in your event handlers and adding/removing classes to all the panels. Instead, you can work with “event delegation” where you set up just one event handler at a common ancestor of all the panels and let the event “bubble” up to that ancestor and be handled there. Also, because the code for the show and the hide are so similar, you can just have one function for both.

Lastly, innerText is not a great name for a variable as innerText is actually a DOM element property name.

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement