Reputation: 1
I have the following HTML:
<div class="col-lg-3 col-xs-6 individual " style="display: block;">
<button style="position:relative; z-index:4; padding:8px 7px 8px 30px; font-size:16px; font-family: Calibri,Arial,Tahoma; color:black;" class="excel-button">Bajar Tabla</button>
<!-- small box-->
<div data-name="cardColor" class="small-box bg-purple">
<div class="inner">
<h4 data-name="title">Semana 9</h4>
<p data-name="dateRange">26-febrero al 02-marzo</p>
</div>
<div class="icon"><i data-name="week" class="fa">9</i></div>
<a class="small-box-footer" data-name="commentFooter">Sin enviar a revisión <i class="text-warning fa fa-exclamation-triangle"></i></a>
</div>
<div class="comment-box text-left" style="display: none;">
<div data-name="comment" class="comment-inner text-danger" style="margin-right:15px">Este reporte no ha sido enviado a revisión</div>
</div>
</div>
The outer div is a clickable div, and I am trying to make the inner button clickable too. But when I click the button it triggers the actions of the div instead of the button's actions. How can I make it so when the user clicks the button it ignores the div element?
Upvotes: 0
Views: 70
Reputation: 162
Here you go. Try clicking on both div
and button
$(function(){
$('div').click(function(event){
alert('clicked on div');
});
$('button').click(function(event){
event.stopImmediatePropagation(); //This ensures that div's onclick event is not fired
alert('clicked on button');
});
});
div{
padding: 20px;
background: #f4f4f4;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<button>Button</button>
</div>
Upvotes: 0
Reputation: 312
This is called event bubbling. When an event occurs on an element, the handler will run on the initial element, then it will bubble up to parent elements that have the same event. Most events bubble up, with the exception of some, e.g. focus
. So your initial button click handler will fire, and then your div click will fire.
To stop propogation, call stopPropagation()
on the event object.
Bubbling is where events propagate upwards in the DOM tree, capturing is where events propogate down.
See here for more information.
Upvotes: 2