javascripthtmlcssevent-bubblingstoppropagation

How to prevent event bubbling in javascript


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.


Solution

  • 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";
    }