Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JQuery on click area – don't trigger click event when clicking specific child element?

I have an HTML block that has a little X icon in the corner. When the user clicks within this area I call a function, but I DON’T want to call this function when clicking the X that sits within that area. Here’s my example simplified:

html:

<ul id="team_members">
    <li class="member">
        <span>Some text</span>
        <span>Some text</span>
        <span>Some text</span>
        <i class="icon-remove"></i>
    </li>
</ul>

jquery:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$("#team_members").on('click', ".member:not(.icon-remove)", function(e) {
    //some code
    alert("clicked!");
 });

What I am hoping will happen, is that clicking anywhere in the "member" <li> will trigger my onclick function but when I click the "icon-remove" the function will NOT be triggered, as I want a different function to trigger there.

>Solution :

The issue with your code is that you are matching a .member element which is not .icon-remove where what you want is a child of .member which is not .icon-remove. So you just need a space between .member and :not(.icon-remove) in the selector:

$("#team_members").on('click', ".member :not(.icon-remove)", function(e) {
    //some code
    alert("clicked!");
 });
 
$("#team_members").on('click', ".member .icon-remove", function(e) {
    //some code
    alert("deleted!");
 });
.icon-remove:after {
  content: 'delete';
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="team_members">
    <li class="member">
        <span>Some text</span>
        <span>Some text</span>
        <span>Some text</span>
        <i class="icon-remove"></i>
    </li>
</ul>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading