Currently I have a div element that contains two( ) images. One image has a z-index of 1, and is behind the other. I want to trigger an event listener when you click on only the first image.
When I click on the smaller image with a z-index of 2, the event listener of the z-index 1 image occurs. link to site: hi2.aisliniscool.repl.co relevant JS code:
const champDiv = document.createElement('div');
const champImg = document.createElement('img'); //(z-index 1)
const favButton = document.createElement('img');
champDiv.addEventListener('click', toggleDiv);
favButton.addEventListener('click', favoriteChamp); //(z-index 2)
favButton.addEventListener('click', setCookie);
favButton.src = "/ext/icons/transparent.png";
favButton.classList.add('favButton');
champDiv.classList.add('champdiv');
champImg.classList.add('champion');
If I click on favButton, toggleDiv and favoriteChamp executes, but I only want favoriteChamp to execute.
CodePudding user response:
You have a problem of bubbling.
You need to stop the parents' events from triggering when you trigger their child event.
You are either gonna need this:
event.stopPropagation()
or this:
event.stopImmediatePropagation()
To fully comprehend what's going and how to handle propagation you can read the following:
https://javascript.info/bubbling-and-capturing
https://www.freecodecamp.org/news/event-propagation-event-bubbling-event-catching-beginners-guide/