2

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
}
Mag
  • 297
  • 1
  • 5
  • 19
  • Please format your question better. If you want to add comments to the code, use comment tags, i.e. `/* */` or `//` so the syntax highlighting works properly. – nem035 Jun 02 '17 at 15:27
  • We'd also like a [mcve] in your question – j08691 Jun 02 '17 at 15:27
  • Possible duplicate of [Event on parent, click child (event bubbling)](https://stackoverflow.com/questions/27275279/event-on-parent-click-child-event-bubbling) – Michelangelo Jun 02 '17 at 15:34

2 Answers2

7

Use preventDefault and stopPropagation.

$('#child_id').on('click', function (e) {
            e.preventDefault();
            e.stopPropagation();
});
JF it
  • 2,403
  • 3
  • 20
  • 30
5

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">
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98
  • Thank you. One more question. How Can I handle css hover on mobile devices on the same example. Click Me appears on parent hover. – Mag Jun 02 '17 at 15:40
  • @Mag No problem. About your second question. I'm not good at css esp when it comes to mobile browsers. You better ask another question with corresponding tags, I guess. – Yury Tarabanko Jun 02 '17 at 15:44