4

There are two nested elements, both have different click actions.
I need to stop outer element action when inner element is clicked.

HTML:

<div id='out'>
    <div id='in'></div>
</div>

jQuery:

$('#out').click(function(){alert('OUT div is pressed')})
$('#in').click(function(){alert('IN div is pressed')})

I need when in is pressed, only his action is executed. out's script should have no action.

How it can be solved?

Nicola Peluchetti
  • 76,206
  • 31
  • 145
  • 192
Qiao
  • 16,565
  • 29
  • 90
  • 117

4 Answers4

8

You should use stopPropagation():

$('#in').click(function(e){
   alert('IN div is pressed')
   e.stopPropagation();
});
alexn
  • 57,867
  • 14
  • 111
  • 145
1

event.stopPropogation() should be able to help you.

Lithium
  • 5,102
  • 2
  • 22
  • 34
0

I think you should do this:

$('#out').click(function(){alert('OUT div is pressed')})
$('#in').click(function(event){
alert('IN div is pressed');
event.stopPropagation();
}
)

Look here for reference

Nicola Peluchetti
  • 76,206
  • 31
  • 145
  • 192
0
$('#out').click(function(){
    alert('OUT div is pressed');
});
$('#in').click(function(){
    $('#out').unbind('click');
    alert('IN div is pressed');
});

or you could stop the propagation of the event, but you can't know for sure which event handler will be triggered first (capture vs bubble events) :

$('#in').click(function(e){
    e.stopPropagation();
    alert('IN div is pressed');
});
gion_13
  • 41,171
  • 10
  • 96
  • 108