-1

I've an anchor within an list-item. Both elements have an event. I'd like to avoid clicking the list-item when clicking the anchor within.

I'd like to avoid chaos. I found this functions but I wasn't able to use them as I wanted:

That's the code:

// HTML
<ul>
    <li id="1">Item #1 <a href="" class="delete">[DEL]</a></li>
    <li id="2">Item #2 <a href="" class="delete">[DEL]</a></li>
    <li id="3">Item #3 <a href="" class="delete">[DEL]</a></li>
    <li id="4">Item #4 <a href="" class="delete">[DEL]</a></li>    
</ul>

// JS
$("ul").sortable();

$(document).on("click", "li", function() {
    alert("list-item clicked.");
});

$(document).on("click", "a.delete", function(e) {
    e.preventDefault();
    if (confirm("Del?")) {
        alert("list-item clicked.");
    }
    // do nothing
});

Here's a fiddle: http://jsfiddle.net/UtE87/1/

What's the best way?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Mr. B.
  • 8,041
  • 14
  • 67
  • 117

2 Answers2

2

It is because of the event propagation, you need to stop the event propagation. It can be done by calling e.stopPropagation() but since you are preventing the default action also, you can do both by returning false from the event handler

$(document).on("click", "a.delete", function(e) {
    if (confirm("Del?")) {
        console.log("list-item a clicked.");
    }
    // do nothing

    return false; //prevent default and stop propagation
});

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • That simple, wow. Shame on me. Thanks, I'll accept your answer as soon as I'm allowed to! – Mr. B. Aug 21 '13 at 16:54
  • 2
    @Mr.Bombastic: Note that this only works because jQuery is doing some magic in the background. You are using *event delegation*, so both handlers are bound to the same element. Without jQuery, `e.stopPropagation()` wouldn't work here (unfortunately the documentation doesn't explain what exactly happens). – Felix Kling Aug 21 '13 at 16:56
1

You can check which element was click on and only run the list item click function if the delete element wasn't clicked.

Demo: http://jsfiddle.net/k5sdC/1/

jQuery:

$(document).on("click", "li", function(e) {
    if (!$(e.target).is('a.delete')){
        alert("list-item clicked.");
    }
});
Hirshy
  • 367
  • 3
  • 16