Note that there are some explanatory texts on larger screens.

plurals
  1. POAvoiding the 'double event' when LABELS are clicked within an element with a click event
    text
    copied!<p>I have some HTML that looks like this:</p> <pre><code>&lt;ul class="toggleList"&gt; &lt;li&gt;&lt;input type="checkbox" name="toggleCbx1" id="toggleCbx1" /&gt;&lt;label for="toggleCbx1"&gt;Item 1&lt;/label&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>I'm using jquery to attach a click event to the LI that will then modify some classes and check or uncheck the checkbox within. </p> <p>I attach the click event as such:</p> <pre><code>$("ul.toggleList li").click(function(){toggleStuff($(this));}) </code></pre> <p>This works fine if I click anywhere in the LI. However, if I click on the LABEL within the LI, my click event is called twice.</p> <p>Why is that? I think it's related to some sort of event bubling-up, correct?</p> <p>As such, is the solution to use .triggerHandler? I've done some reading on it and looked at some examples but I don't quite understand the proper syntax for setting it up. </p> <p>ADDENDUM: </p> <p>Sam pointed out an option that I think leads to the solution. This maybe isn't a triggerHandler issue.</p> <p>What appears to be happening is that (by default?) clicking on a LABEL will bubble-up a click event. The solution appears to be to check to see if the event was triggered by the label and, if so, over-ride that.</p> <p>Doing some testing:</p> <pre><code>[...].click(function(evt){ console.log(evt.target); if ($(evt.target).not("label")) { console.log("not label?"); doMyThing($(this)); }else{ console.log("is label?"); }; </code></pre> <p>The above doesn't work. Whether I click on the LABEL or another element, it thinks it's <em>not</em> the label. </p> <p>Oddly, reversing the logic <em>does</em> work:</p> <pre><code>[...].click(function(evt){ console.log(evt.target); if ($(evt.target).is("label")) { console.log("is label?"); }else{ console.log("not label?"); doMyThing($(this)); }; </code></pre> <p>Any idea what that is? I'll do more testing...</p> <p>FINAL ADDENDUM:</p> <p>Argh! User error. I, erroneously, assumed '.not' did the opposite of '.is'. Well, that's not true. .is does a comparison and returns a boolean. .not removes elements that matches (and therefore returns objects).</p> <p>So, I guess one always has to check for .is and use an else when testing for 'not is'</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload