2

Given the following HTML snippet:

<li class="list">
  <img src="/assets/img/site/arrow_black.png"/>My List Element<span class="star"></span>
</li>

When I bind a click event to the li element and also bind a click event to the .star class, my question is the following:

How do I stop the click event on the li firing when I click on the star?

My JQuery code looks something along the lines of:

$(".list").click(function() {
//do something
}

$(".star").click(function() {
//do something
}
Shawn Chin
  • 84,080
  • 19
  • 162
  • 191
panthro
  • 22,779
  • 66
  • 183
  • 324
  • possible duplicate of [Javascript/jQuery Click Element within Element](http://stackoverflow.com/questions/3408138/javascript-jquery-click-element-within-element) – Shawn Chin Apr 25 '12 at 12:52
  • and many others, e.g. http://stackoverflow.com/questions/1164213/how-to-stop-event-bubbling-on-checkbox-click and http://stackoverflow.com/questions/3460197/jquery-disabling-click-function-on-parent-element/3460215#3460215 – Shawn Chin Apr 25 '12 at 12:54
  • lol, maybe jQuery needs more documentation on this? – SpYk3HH Apr 25 '12 at 13:03

4 Answers4

10

See jQuery.stopPropagation()

$(".star").click(function(e) {
    e.stopPropagation();
    // do work
}
epascarello
  • 204,599
  • 20
  • 195
  • 236
SpYk3HH
  • 22,272
  • 11
  • 70
  • 81
1

Try event.stopPropagation();

$(".star").click(function(event) {
  event.stopPropagation();
  // Do something
}
John Conde
  • 217,595
  • 99
  • 455
  • 496
0

You need to stop the even propgagation for .star.

http://api.jquery.com/event.stopPropagation/

$(".star").click(function(ev) {
    ev.stopPropagation();
});
GillesC
  • 10,647
  • 3
  • 40
  • 55
0

You can use the event delegation ..

Apply the event listener to the ul

document.getElementById("parent-list").addEventListener("click",function(e) {

if(e.target && e.target.nodeName == "LI") {
    var classes = e.target.className.split(" ");

    if(classes) {

      for(var x = 0; x < classes.length; x++) {

        if(classes[x] == "star") { // do your thing
                                  }
                    }
          }
  }
});

});

or just use preventDefault to star class

Kunal Vashist
  • 2,380
  • 6
  • 30
  • 59