Mag
Mag

Reputation: 297

Prevent parent click when click on child

I want to prevent parent click when I clicking on child SPAN. I tried

    e.stopPropagation

    and thi way

    if (!e) e = window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();

I have html like:

 <label for="parent_id"> Some text
   <span id="child_id">Click child</span>
 </label>
 <input id="parent_id" />

Function for Parent element

$('#parent_id').click(function (e) { SomeParentCode }

Function for Child element.

$('#child_id').click(function (e) {
      e.stopPropagation();
       But I what to prevent parent click
       SomeChildCode
}

Upvotes: 2

Views: 10795

Answers (2)

JF it
JF it

Reputation: 2403

Use preventDefault and stopPropagation.

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

Upvotes: 7

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

You need to prevent default action (which is focusing on input) by calling ev.preventDefault

$(function() {
  $('#child').click(e => {
    e.preventDefault()
    
    console.log('click on child')
  })
  
  $('#parent').click(() => {
    console.log('click on parent')
  })

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="parent">
  <span id="child">Click Me</span>
</label>
<input type="text" id="parent">

Upvotes: 5

Related Questions