0

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 ?

abu abu
  • 6,599
  • 19
  • 74
  • 131

3 Answers3

2

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.

Tân
  • 1
  • 15
  • 56
  • 102
1

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>
0

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);
       }
});
Ayaz Ali Shah
  • 3,453
  • 9
  • 36
  • 68