abu abu
abu abu

Reputation: 7052

Parent & child .click() method

I have below HTML code.

<li class="list-group-item font-weight-bold">
    Mouse
    <img src="images/delete.png" class="delete"/>
</li>

I have 2 different jQuery .click() method. One for the <li></li> and another for <img/>.

Now when I click on <img/> , then <li></li> .click() method also running.

Here is the jQuery code.

$('.list-group li').click(function () {
    //some code here    
});

 $('.delete').click(function () {
    //some code here 
});

How can I keep them separate, so that each .click() method run individually ?

Upvotes: 0

Views: 69

Answers (3)

Sepehr Amirkiaee
Sepehr Amirkiaee

Reputation: 132

Use event.stopPropagation() method.

This method prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. jQuery API Documentation

$('li.list-group-item').on('click',function(){
  console.log('LI Clicked')
})

$('img.delete').on('click',function(event){
  event.stopPropagation()
  console.log('IMG Clicked')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<li class="list-group-item font-weight-bold">
    Mouse
    <img src="images/delete.png" class="delete"/>
</li>

Upvotes: 1

Ayaz Ali Shah
Ayaz Ali Shah

Reputation: 3541

Suppose you have different id attribute on both and same class .click

<li class="list-group-item font-weight-bold click" id="this_is_li">
    Mouse
    <img src="images/delete.png" class="delete click" id="this_is_img"/>
</li>

When you click on element below script will let you know about that element id so you can use it.

$('.click').on('click', function(){
       var ID = $(this).attr('id'); 
       if(ID === 'this_is_li'){
           alert('you clicked on li #' +ID);
       }
       if(ID === 'this_is_img'){
           alert('you clicked on img #' +ID);
       }
});

Upvotes: 0

T&#226;n
T&#226;n

Reputation: 1

You can try to use this way:

var li_onclick = function (li) {
  console.log(li);
};

var img_onclick = function (img) {
  console.log(img);
};

$(document).on('click', function (e) {
  if (e.target.tagName === 'LI') {
    li_onclick(e.target);  
  } else {
    img_onclick(e.target);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<li class="list-group-item font-weight-bold">
    Mouse
    <img src="images/delete.png" class="delete"/>
</li>

Using e.target to check which the element was clicked. Then, checking tagName to classify li tag and img tag.

Upvotes: 2

Related Questions