How to prevent event bubbling in javascript
Asked Answered
H

3

9

thanks for reading... I'll get right into the issue.

I have an onclick function attached to an image.

<div id="mercury" onclick="displayCreations()">

Javascript function:

function displayCreations(){
   document.getElementById("projects").style.display = "block";
}

The div I'm displaying as a block is set to none once you arrive at the page. This function sets the display to block, which works.

I'm having trouble with making an onclick function for an image inside the div that sets the display value back to none. This doesn't seem to work with my current code...

HTML:

<div id="mercury" onclick="displayCreations()">
        <img id="exit" onclick="hideCreations()" src="./assets/images/exit.png" alt="exit button" title="Leave Planet: Mercury" />
        <div id="projects">
            <h3>No creator here, but it looks like you've found some his wonderous creations...</h3>
            <ol>
                <li>Project 1</li>
                <li>Project 2</li>
                <li>Project 3</li>
            </ol>
        </div>
    </div>

Javascript:

function displayCreations(){
   document.getElementById("projects").style.display = "block";
}

function hideCreations(){
   document.getElementById("projects").style.display = "none";
}

When I run this site on google chrome and click the 'exit' button, nothing happens and nothing is displayed in the error messages.

This link leads you to a well-known site, Gyazo, where you can find a gif of what I see on my end.

Link: Link

I'd prefer a javascript solution for my current code, and perhaps you can explain to me why this is happening so I don't get into the same situation again.

Holladay answered 18/1, 2018 at 19:33 Comment(2)
It's because your img is inside of mercury, so when you click img (inner element which is contained inside of mercury) the click event bubbles up and triggers the click event on mercury. if you put console log lines, you will see what's happening. You just need to stop the bubbling in the img handler jsfiddle.net/qmxhfpwhLodgings
@Lodgings That was the issue, thank you very much.Holladay
K
20

It is caused due to event bubbling.Triggering an event on child propagates upward toward its parent.In your case click event on image also triggers click event on parent div.use event.stopPropagation() to prevent this from happening.

HTML :

pass the event as parameter to event listener function

<img id="exit" onclick="hideCreations(event)" src="./assets/images/exit.png" alt="exit button" title="Leave Planet: Mercury" />

JS:

Capture the event and call it's stopPropagation method

function hideCreations(event){
   event.stopPropagation();
   document.getElementById("projects").style.display = "none";
}
Kab answered 18/1, 2018 at 19:43 Comment(0)
B
3

A very useful solution from AL-zami. It's also useful outside the function e.g. onclick="event.stopPropagation();yourFunction(existing parameterset)". So You don't need to change yourFunction and it's parmeterlist, nor the other calls of it in the code. It's even possible to create an extra container (e.g. div) around different events to prevent bubbling. e.g.:

  <div id="picBigOLL" onclick="previousPict();">
    <div id="picBigPlay" onclick="event.stopPropagation();">
      <div id="playButsBox">
        <div id="bPPlayL" onclick="diaPB(-1)">
          ⯇
        </div>
        <div id="bPPlayS" onclick="diaPB(0)">
          ||
        </div>
        <div id="bPPlayR" onclick="diaPB(1)">
          ⯈
        </div>
      </div>
    </div>
Bel answered 22/4, 2020 at 20:43 Comment(0)
W
0

Inline attributes are dirty.

Try something like this:

//your function
function hideCreations(){
   document.getElementById("projects").style.display = "none";
}
//initializing your website by assigning event-listeners to elements
function init(){
   //assign an listener to the click-event of your element
   document.getElementById("exit").addEventListener("click",function(event){
      //stops all other listeners from firing
      event.stopImmediatePropagation();
      //execute your function
      hideCreations();
   }
}
//calls the init-function, once the document is ready
document.onreadystatechange = init;

For more info check out: https://blog.webdevsimplified.com/2022-01/event-listeners/

Wiliness answered 21/8, 2023 at 14:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.