Search code examples
javascriptdomonclickdom-eventsonclicklistener

How to add event listeners to elements that are inside one another


This image is to explain what my problems is:

I have a Detail-box and I have added the "click" event listener to it. I want to jump to another page when anyone clicks this link. Also, I what to add "click" event-listener to the button inside this box (for doing some other action).

The problem is whenever I click on the button the event-listener corresponding to the the box runs and the event-listener corresponding to the button does not.

How do I solve this problem? Any help would be great.


Solution

  • If I understood correctly, you are looking for event.stopPropagation() event property.

    MDN Documentation link on Event.stopPropagation()

    JSFiddle Example

    const detailsAlert = e => {
        alert('details alert!');
    }
    
    const buttonAlert = e => {
    e.stopPropagation();
    alert('button alert!');
    }
    
    document.getElementById("details").addEventListener('click', detailsAlert, false)
    
    document.getElementById('btn').addEventListener('click', buttonAlert, false);