0

I have lis containing anchor tags for deleting that particular li. So, I have onclick event for both anchor tag and li. Clicking on li opens up a modal window and click on anchor tag is supposed to hide that li.

How can I trigger click event on anchor tag without it triggering li click event. Here is what I have tired so far:

JS:

$('body').on('click', 'a', function(e) {
    if(confirm('Are you sure you want to delete it?') == true){
        $(this).parent().hide();
    }
    //e.preventDefault();     
    e.stopPropagation();   
});

HTML:

<li onclick="openModal(0)">
  <a class="closer">X</a>
  <h3>Lolita</h3>
  <p>Check it</p>
</li>
rrk
  • 15,677
  • 4
  • 29
  • 45
Milan Kumar
  • 77
  • 1
  • 6
  • 1
    Possible duplicate of [jQuery on() stopPropagation not working?](http://stackoverflow.com/questions/8995008/jquery-on-stoppropagation-not-working) – Script47 Feb 22 '16 at 12:40
  • Maybe you could post the code which is excuted when clicking the `li`. I reproduced your code, and it does not trigger a click on the `li` after clicking on the `a`. – Pit Feb 22 '16 at 12:48

1 Answers1

1

Here's a fiddle with your answer: https://jsfiddle.net/jimedelstein/bsg4jq3m/

You need to detect the target of the click, and if it's the link ignore it, otherwise trigger the li click.

<li>
  <a class="closer">X</a>
  <h3>Lolita</h3>
  <p>Check it</p>
</li>


$('body').on('click', 'a', function(e) {
    if(confirm('Are you sure you want to delete it?') == true){
        $(this).parent().hide();
    } 
    e.stopPropagation();   
});

function openModal(e){
    if (e.target != $("a.closer")[0]){
     alert("not the link!");
  }
};

$("li").on("click", openModal);
Jim Edelstein
  • 792
  • 6
  • 10