0

In My jquery function i used to trigger click function from li and img seperately but unfortunately when i click image. Click function for list also triggers

HTML CODE:

  <li id="list_id">List_text<img src='image.jpg' id="img_id"></li>

Jquery function:

$("#list_id").click(function(){
 alert('List is clicked');
});

$("#img_id").click(function(){
 alert('Image is clicked');
});

Once i click image both function triggers.

*Question:*I need to trigger only click function for image once i click image and to trigger click function for list once i click list

1
  • i somewhere read stopPropagation is better than return false ,i will get you the link Commented Dec 7, 2010 at 8:03

3 Answers 3

2

You need to stop the event propagation:

$("#img_id").click(function(evt){
    alert('Image is clicked');
    evt.stopPropagation();
});
Sign up to request clarification or add additional context in comments.

2 Comments

Still it calls li click function. Since i get li and img from ajax. i think its not working
What do you mean that you are getting li and img from AJAX? When do you attach the click handler? And here's a working demo.
0

use event.stopPropagation();

     $("#img_id").click(function(){
             alert('Image is clicked');
  event.stopPropagation();
            });

1 Comment

Still it calls li click function. Since i get li and img from ajax. i think its not working
0
$("#img_id").click(function(){
  alert('Image is clicked');
  return false;
});

Just return false from the function, which will prevent the event from bubbling up (among preventing other default actions, if that's what you want).

2 Comments

stopPropagation is better than return false as it kills all the futured...events for that
@gov Depends on what exactly the OP wants, added a note to my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.