use event.stopPropagation()
:
$('body').on('click', '#button', function(e){
e.stopPropagation();
alert('button');
});
Вопрос
I have problem with jQuery click events.
I think solution is easy, but it's hard to find and right formulate in english.
So this HTML code:
...
<div id="element">
<div id="button">
</div>
</div>
...
CSS code:
#element{
width: 100%;
height: 100%;
position: absolute;
}
#button{
width: 64px;
height: 64px;
position: absolute;
left: 50%;
}
jQuery Code:
$('body').on('click', '#element', function(){
alert('element');
});
$('body').on('click', '#button', function(){
alert('button');
});
And Execution:
if i click on #button it shows to me two alerts ('element') and ('button'), but if i click on #button i don't want click action from #element.
Thanks for any response
Решение
use event.stopPropagation()
:
$('body').on('click', '#button', function(e){
e.stopPropagation();
alert('button');
});
Другие советы
Use an if statement on click to show the button alert if it is the button that is clicked, else show other alert.
#button
is child of #element
<div id="element">
<div id="button"></div>
</div>
Try doing this way
<div id="element">Element</div>
<div id="button">Button</div>
$('body').on('click', '#element', function(){
alert('element');
});
$('body').on('click', '#button', function(){
alert('button');
});
try this
$('body').on('click', '#button', function(){
alert('button');
return false;
});
Try to stop propagation of children's events in parents
$('body').on('click', '#element', function(e){
e.stopPropagation();
alert('element');
});
$('body').on('click', '#button', function(e){
e.stopPropagation();
alert('button');
});