bagofmilk
bagofmilk

Reputation: 1550

Button on top of Anchor - How to prevent Default click?

I have a button on top of an anchor (image)

I have an alert for each (the button and the anchor).

After I click the button, the anchor then follows with its alert too. How do I prevent the anchor from initiating after I click the button?

see jsfiddle --> http://jsfiddle.net/EhWZc/

HTML:

<a href='#' onclick='alert("Im an anchor");'>
   <button id='delBtn' onclick="alert('Im a button');">x</button>
   <img src='http://www.extremetech.com/wp-content/uploads/2013/05/image-1.jpg' style='width:200px;'/>
</a>

Upvotes: 0

Views: 1297

Answers (1)

Suresh Ponnukalai
Suresh Ponnukalai

Reputation: 13998

In this case you need to use stopPropagation function instead of preventDefault like below.

 $('#delBtn').on('click', function(e){                   
        e.stopPropagation();  
});

stopPropagation stops the event from bubbling up the event chain.

preventDefault prevents the default action the browser makes on that event.

DEMO

Upvotes: 2

Related Questions