0

I am using jQuery for a list and a div element click. HTML code is-

<ul class="list-group">
    <li class="list-group-item">
        <div>
            <div>
                Anything <img id="image_click" src="http://www.neatimage.com/im/lin_logo.gif">
            </div>
            <div>
                More thing
            </div>
        </div>
    </li>
    <li class="list-group-item">Documents</li>        
    <li class="list-group-item">Music</li>
    <li class="list-group-item">Videos</li>
</ul>

And jQuery code is-

$( document ).ready(function()
{
    $(".list-group-item").click(function()
    {
        alert($("For list");
    });

    $("#image_click").click(function()
    {
        alert("for image");
    });
});

When I click on a li item, only For list is alerted. But if I clicked on image, then for image and after that For list is alerted.

What I want is if anyone click on li element, For list should be alerted, but if he clicks on the image, only for image should be alerted, for list should not be alerted.

1

4 Answers 4

4

It is because of event bubbling, so you stop it by calling Event.stopPropagation()

$("#image_click").click(function (e) {
    e.stopPropagation();
    alert("for image");
});
Sign up to request clarification or add additional context in comments.

3 Comments

Isn't stopping propagation not a good idea to do? Shouldn't there be a better way to handle this? css-tricks.com/dangers-stopping-event-propagation
@crazymatt you can always check whether the click happened in a particular element and then choose not to do anything
@crazymatt something like - jsfiddle.net/arunpjohny/gyr6g1p1/1 - or more generalized jsfiddle.net/arunpjohny/gyr6g1p1/2
1

use stopPropagation(); : to stop bubbling event

 $("#image_click").click(function(e)
    {
       e.stopPropagation();
        alert("for image");
    });

Comments

0

If you do not want any action from any action that simply write return false. which will prevent from multiple triggering your function code.

 $(".list-group-item").click(function(){
       return false;
    });

$("#image_click").click(function(){
     alert("for image");
});

1 Comment

0

Or you can try this code:

$(".list-group-item").click(function (e) {
    if(this==e.target)
         alert("for list");
});  

I think this question may help you.

Comments

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.