I want to remove overlay when i was clicking and the image but it didn’t. The overlay dissapearing when i clicked on div (overlay) but not when I clicked on photo.The console didn’t show me errors.
It would be more useful to have the HTML that’s being output, rather than the PHP generating it, that way I can quickly set up a demo to look at what’s going on.
I knocked up a quick Codepen with some minimal markup in it just to see what’s happening. As described, when clicking on the image in the markup, the overlay appears. The overlay will clear when the overlay itself is clicked, it doesn’t though when the image set in the overlay is clicked.
I’ve not got an immediate solution for you, but I did add a line into the event listener to log out where on the overlay it will respond to a click event. Seemingly, it responds when the image is clicked, which makes it a bit of a puzzle as to why the function attached to the listener isn’t run.
overlay.addEventListener('click', function() {
console.log('Logged from ' + overlay);
overlay.parentElement.removeChild(overlay);
});
The overlay is being removed when you click on the image, but it’s immediately being re-added, which is why it appears that nothing is happening.
Here’s what’s happening:
The first click creates and displays the image overlay
A click handler is added to the overlay
Clicking the overlaid image fires the handler to remove it
The click handler on the window object then fires in response to the same click, and re-adds the overlay
One way to prevent this is to avoid adding the first click handler to the window object, and instead add it to the image. Alternatively, you can call stopPropagation() on the event, to stop it from travelling up from the overlay to the window (as events ‘bubble’ up the DOM from the target):