5

I have a list with div items. each of them redirects to a page when I click it. Now I added a button within the div and I do not want to get redirected when I click the button (i.e. do not execute the parent divs on click event)

<div class='item' onClick="alert('div');">
... div content
    <button class='btn' onClick="alert('button');">Action</button>
</div>

Above code should only alert once when I click the button.

EDIT:

I just realized that my actual problem is even one more level up:

<a href='www.google.at'>
<div class='item' onClick="alert('div');">
    <button class='btn' onClick="alert('button');event.stopPropagation();">Action</button>
</div>
</a>

I need to prevent the href redirection when I click the button. Is there something similar to event.stopPropagation()?

2

1 Answer 1

10

Original answer

You can accomplish this by calling event.stopPropagation()

<div class='item' onClick="alert('div');">
    <button class='btn' onClick="alert('button');event.stopPropagation();">Action</button>
</div>

Answer to edit

Apparently you can stop the propagation to an anchor element by returning false, not sure if this is the proper way, but it works.

<a href='www.google.at'>
<div class='item' onClick="alert('div');">
    <button class='btn' onClick="alert('button');event.stopPropagation();return false;">Action</button>
</div>
</a>

Sign up to request clarification or add additional context in comments.

2 Comments

thank you. It works for the click events, but I just realized that my problem is actually one more level up and related to a href. (please check my edited question)
I just discovered event.preventDefault(); :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.