Does the html label prevent propagation from occurring?

Can anyone explain why the toggle function is not being executed when clicking inside the box with the black border, but works when clicking outside of it (although not on the checkbox)?

var checks = document.querySelectorAll("ul li");

for (var i = 0; i < checks.length; i++) {
  checks[i].addEventListener("click", tog);
};

function tog(e) {
  e.currentTarget.classList.toggle("active");
}
ul li {
  background: #3CF;
  padding: 0.25em 0.5em;
  margin: 0.25em 0;
  display: block;
  cursor: pointer;
  text-indent: 1.5em;
}
ul li.active {
  background: #6EF;
}
label {
  display: block;
  width: 100px;
  border: 1px solid black;
}
<ul>
  <li>
    <label>
      <input type="checkbox">1
    </label>
  </li>
  <li>
    <label>
      <input type="checkbox">2
    </label>
  </li>
  <li>
    <label>
      <input type="checkbox">3
    </label>
  </li>
</ul>

Answer №1

Indeed. As elaborated in my previous response. The repeated invocation of the tog function results from the bubbling effect within the label tag, triggering the addition and removal of the active class in quick succession. This leads to the observed issue.

To witness this behavior first-hand, you can experiment with an alert via this example.


A viable solution to circumvent this problem involves leveraging the event's target property. Here's a functional version available for testing on JSFiddle, tailored to your requirements.

var checks = document.querySelectorAll("ul li");

for (var i = 0; i < checks.length; i++) {
  checks[i].addEventListener("click", tog);
};

var i = 0;
function tog(e) {
        if(e.target.tagName.toLowerCase() == 'label') {
            i++;  //if we remove this then i will never increment
            if(i%2 != 0) {
                i++;  //to bring back to even, so next click should work fine
                return;
            }
        }
  e.currentTarget.classList.toggle("active");
}
ul li {
  background: #3CF;
  padding: 0.25em 0.5em;
  margin: 0.25em 0;
  display: block;
  cursor: pointer;
  text-indent: 1.5em;
}
ul li.active {
  background: #6EF;
}
label {
  display: block;
  width: 100px;
  border: 1px solid black;
}
<ul>
  <li>
    <label>
      <input type="checkbox">1
    </label>
  </li>
  <li>
    <label>
      <input type="checkbox">2
    </label>
  </li>
  <li>
    <label>
      <input type="checkbox">3
    </label>
  </li>
</ul>

You have the option to avoid utilizing the global variable i by implementing an IIFE that returns a function handler or employing closure techniques.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Displaying data on the number of vertices and triangles in the editor interface

Can anyone provide guidance on how to incorporate a legend displaying the number of Vertices and Triangles, as well as a 3 axes helper legend, in Three.js rendering within the example editor? I have attached a screenshot of the scene with these legends for ...

Conflicting styles between Bootstrap and Formstack are causing radio buttons to appear only partially visible

Encountering a conflict between Bootstrap (4.1.3) and Formstack CSS when trying to embed a form in a website. The radio buttons are not fully visible, with the issue located in the "label" class ("fsOptionLabel"). Adjusting the line height provides a parti ...

Transferring a single dataset from a table to a pop-up modal using Angular

I am working on a table to display entries for a contest, extracted from a database using PHP and converted into a .json object for AngularJS and JavaScript. I want to add a modal feature so that when a "judge" clicks on an entry, they can view its details ...

Iterating through images one time and capturing the mouse coordinates for every click made by the user

I have the following code snippet that displays a series of images and I would like to capture the coordinates of each mouse click on these images. Is there a way to send these coordinates to my email at the end of the image loop? Any assistance in achievi ...

Google Maps displays grayscale overlays on the latest version update

Hello, I am facing a challenging issue with the Google Maps API. I have come across some similar threads discussing this problem, but unfortunately, they did not provide a solution that suits my specific case. Currently, I am working on an angular.js 1. ...

Resizing with Jquery results in sudden movement

I have used jQuery to create a set of buttons inside a <ul> element. I am now attempting to resize the <ul> by adding a handle to the top of it, but when I try to resize it, the element jumps as shown in the images below. What could be causing ...

Issues arise while utilizing the execute method in PHPUnit-Selenium2

When creating Acceptance tests with PhpUnit and its Selenium2 extension, I am attempting to utilize the execute method within the PHPUnit_Extensions_Selenium2TestCase class to run Javascript code that checks if the document is fully loaded. Here is an exa ...

Resolve problems with implementing dynamic routes in Next.js

I have been learning about Next.js and I am struggling with understanding how to set up dynamic routing. I have the following setup: https://i.stack.imgur.com/uBPdm.png https://i.stack.imgur.com/YYSxn.png "use client" import React from "reac ...

Connecting users from a mobile website to a particular item within the Amazon application

Recently, I've been working on linking from my mobile site to a particular item within the Amazon app. My JavaScript code includes a try/catch block that redirects users to the webpage if they don't have the app installed. However, I've foun ...

What is the mechanism behind angular2's spa routing functioning seamlessly without the need for the hash character in the url?

During my experience with the Angular2 "Tour of Heroes" tutorial, I made an interesting observation about how their single page application router functions without a trailing hash symbol (#) in the URL. This differs from the Kendo SPA router, which typica ...

Utilizing the Vuetify Dialog Component in a repetitive manner to confirm the deletion of an event

In a project I'm working on, there's a 'datatable.vue' file that loops through data and displays it in a table. Within this loop, I want to implement a reusable dialog component from Vuetify (v-dialog) that will load upon interaction wi ...

Monitoring the validity or errors in AngularJS input fields

I'm attempting to observe the $error or $valid status of a control. Here is the control in question: <form id="myForm" name="myForm"> <input name="myInput" ng-model="myInputMdl" business-validation/> </form> The business-validat ...

The background image is not appearing on the div as expected

I've been attempting to create a div and set a background image for it using jQuery, but I seem to be facing issues. When I try setting the background color to white, it works fine. Here's the code snippet: function appendToDom(poster) { ...

Resource loading unsuccessful: server returned a 405 status code, indicating method not permitted

An error occurs when attempting to send an email using PHP. Failed to load resource: the server returned a 405 (Method Not Allowed) status for sendmail.php This is the form: <form action="sendmail.php" method="post" id="contactform" > <div ...

Error: Trying to use 'search' before it has been initialized causes a ReferenceError

Every time I run my code, I encounter this reference error but I can't figure out what's causing it. ReferenceError: Cannot access 'search' before initialization App C:/Users/GS66/Desktop/IN20/IFN666/week4/src/App.js:60 57 | 58 | expor ...

How to effectively delete the class from a navigation list item

Looking for some inspiration? Check out the basic visuals for this question here. But let me break it down for you. This snippet shows the HTML & CSS behind a tabbed-carousel, with a condensed version for clarity: <style> #myCarousel-100 . ...

Troubleshooting issue with changing class based on input values

It appears that there is an issue with the functionality when switching values on page load. Initially, I was able to make it work for a single switch, but now that there are multiple switches on the page, toggling affects all of them. How can I modify it ...

Enhance your images with a hover zoom effect while viewing an overlay on top

Is there a way to make an image still zoom in on hover even when it has an overlay using CSS? I am currently working with Bootstrap 5.2 Thank you in advance. .trip-card { position: relative; } .trip-card img { border-radius: 30px; } .overlay { ...

Switch out bootstrap icons for angular material icons

I'm currently in the process of transitioning from using Bootstrap to Angular Material in an existing application. I need assistance with replacing the Bootstrap icons with Angular Material icons. Any help is greatly appreciated. <md-button class= ...

The @Input() function is failing to display or fetch the latest value that was passed

I am currently working on an angular project, and I've encountered a situation where I'm attempting to send a value from a parent component to a child component using the @Input() decorator. Despite my efforts, the child component continues to di ...