Skip to content
Advertisement

When clicking on a button inside another button, the functions for both buttons are run

I have show-button that, when clicked, expands and shows some text and a collapse-button:

<button id='show-button'>
    <p>Test</p>
    <button id='collapse-button'></button>
</button>

When show-button is clicked, it expands and shows the paragraph and the collapse button. When the collapse-button is clicked, it collapses back to the original size where it’s all hidden.

The problem is the following:

When I click on the collapse-button, the event listener for click is run and everything collapses. However, for some reason, the event listener of the show-button is also triggered and everything is shown again. A loop. You can show but never collapse it again.

How can I make sure that when collapse-button is pressed, show-button isn’t also triggered?

Thanks

Advertisement

Answer

Inside the “click” function you can stop the propagation of the event so it will not reach the other components
event.stopImmediatePropagation();

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement