Delegating Javascript events when the selector and children are unknown

Having a dynamic selector (linkTrigger) set up to capture clicks on an element, the challenge lies in not knowing what linkTrigger might be or if it will have any children. Previously with jQuery, everything worked seamlessly.

Clicking on the first green rectangle (excluding the numbers part) displays all 3 handlers working as expected. However, clicking on the numbers within the first green rectangle triggers only the jQuery and javascript2 handlers, as anticipated, since clicking on the span in the green box does not meet the condition:

if (e.target.classList.contains(linkTrigger.substring(1))) {

I'm unable to use css pointer-events none on unwanted children because I'm unsure about the nature of linkTrigger and wish to avoid tampering with its contents.

The issue arises with the javascript2 handler being non-dynamic, requiring me to add this handler manually for every new ".a" container added to the DOM later on.

Is there a more effective solution to address these challenges?

var linkTrigger = '.c'

//jquery works fine and reacts in real-time

$('.wrap').on('click', linkTrigger, function(e) {

  var parent = $(this).closest('.a'),
    id = parent.attr('data-id')

  console.log('jquery: ' + id)

})

//javascript functions properly except when clicking on children (number spans inside the green rectangle) even though it is reactive. I cannot apply **css pointer-events none** to prevent click events on certain children due to uncertainty regarding **linkTrigger**, nor do I want to modify its contents.

document.querySelector('.wrap').addEventListener('click', function(e){

  if (e.target.classList.contains(linkTrigger.substring(1))) {
    var parent = e.target.closest('.a'),
      id = parent.getAttribute('data-id')

    console.log('js: ' + id)
  }

})

//javascript2 works but lacks reactivity, necessitating manual attachment of this function call to each item when additional ".a" containers are added.

document.querySelectorAll(linkTrigger).forEach(function(el){

   el.addEventListener('click', function(e){

       var parent = e.target.closest('.a'),
      id = parent.getAttribute('data-id')

        console.log('js2: ' + id)

   })
})
.a{
  
  width:300px;
  height:300px;
  background:red;
  margin:1px;
  
}
.b{
  
  width:200px;
  height:200px;
  background:blue;
  
}
.c{
  
  width:100px;
  height:100px;
  background:green;
  
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="wrap">

  <div class="a" data-id="0">
    <div class="b">
      <div class="c"><span>657567645</span></div>
    </div>
  </div>

  <div class="a" data-id="1">
    <div class="b">
      <div class="c"></div>
    </div>
  </div>

</div>

Answer №1

event.target is the exact element that was clicked on. When you click on the span within the element, you are targeting the span specifically, not the parent element.

In order to capture the click on the span, you can utilize the closest() method similar to how you target the anchor tag.

var linkTrigger = '.c'

//jquery works fine and its live

$('.wrap').on('click', linkTrigger, function(e) {

  var parent = $(this).closest('.a'),
    id = parent.attr('data-id')

  console.log('jquery: ' + id)

})



document.querySelector('.wrap').addEventListener('click', function(e){

  if (e.target.closest(linkTrigger)) {
    var parent = e.target.closest('.a'),
      id = parent.getAttribute('data-id')

    console.log('js: ' + id)
  }

})
.a{
  
  width:300px;
  height:300px;
  background:red;
  margin:1px;
  
}
.b{
  
  width:200px;
  height:200px;
  background:blue;
  
}
.c{
  
  width:100px;
  height:100px;
  background:green;
  
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="wrap">

  <div class="a" data-id="0">
    <div class="b">
      <div class="c"><span>657567645</span></div>
    </div>
  </div>

  <div class="a" data-id="1">
    <div class="b">
      <div class="c"></div>
    </div>
  </div>

</div>

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

Having difficulty displaying a loading message upon generating a new screen

Recently, I encountered a challenge on my website where I needed to perform a lengthy computation upon clicking a button in client-side JavaScript. I wanted to display a loading message while the computation was running, so I implemented the following code ...

When content editable is assigned a value, it skews the direction of the writing

I am currently working on an editable text component with the 'editable' attribute. However, I am facing an issue where the text is not aligning in the correct direction as I type - the first character always ends up at the end of the text. Expe ...

Pictures are floating to the side instead of being centered in mobile mode

When in desktop mode, one img is aligned to the left and the other one is aligned to the right. However, when viewed on a phone, I am attempting to center align them but they continue to be aligned to the sides. What could be the issue here? Provided be ...

Error encountered with special character encoding in ajax request

When attempting to retrieve a JSON file with special characters through an AJAX call, some of the characters are being converted to in the success callback. The content-type has been set as: application/json;charset=UTF-8. Here is the content of the m ...

Creating interactive tables in JavaScript with dynamic row adding, editing and deleting capabilities

Whenever I try to add a new row by clicking the Add Row button, an error occurs. My goal is to append a new 'tr' every time I click the add row button. Each 'td' should include a checkbox, first name, last name, email, mobile number, ed ...

Error: Material UI search bar doesn't refresh interface

I implemented Material UI's auto complete component to create a dynamic select input that can be searched. The component is fed options in the form of an array consisting of strings representing all possible choices. <Grid item xs = {props.xs} cla ...

"Encountering an issue with AJAX file upload displaying an error message for

Before I showcase my code, allow me to explain my objective. My goal is to create a page that updates a user's details in the database using AJAX. Initially, I successfully achieved this task. Subsequently, I wanted to enhance the functionality by inc ...

Error: Attempted the use of 'append' method on an object lacking the implementation of FormData interface, with both processData and contentType set to false

Apologies for any English errors. I am attempting to use ajax to submit a form, and here is my JavaScript code: $("#formPublicidad").on('submit', function(event) { event.preventDefault(); var dataForm = new FormData(document.getElementBy ...

The Optimal Approach for Importing Libraries across Multiple Files

I have two files - one containing the main code execution, and the other solely consisting of a class. For instance: File_1: const _ = require('underscore'), CoolClass = require('CoolClass'); _.map(//something) Files_2: const _ = ...

Equalizing the width of the border to match the width of the text

After designing a menu using a website builder with custom CSS, I found that the HTML code generated automatically by the builder needed some tweaking. Upon inspecting the code, I discovered the following structure: <div class="elementor-container elem ...

Could someone help me understand why my div elements are auto-indenting after the initial row?

Encountering a rather peculiar issue here. It's worth mentioning that I am using Shopify, which has been known to cause some odd problems in the past. Currently, I am working on this page for coding purposes (though not the final placement) - On thi ...

In Apostrophe CMS, articles are only visible to logged-in users, the author's information remains hidden to non-

After utilizing Apostrophe CMS for my project, I have been consistently developing new pages and articles. This content is meant to be accessible to both the general public (non-logged-in users) and logged-in users (administrators). While I grasp the fund ...

Issues with keyboard accessibility in drop down menus

Looking to improve the keyboard accessibility of my menu bar. Swapped out all instances of :hover with :focus, but unfortunately dropdown menus are still not accessible via keyboard. Does anyone have a solution for this issue? Appreciate any help! ...

Prompt user to save changes or cancel before closing modal (if closed by pressing ESC or clicking the backdrop)

When I manually close the modal, everything works fine. I just create a prompt and only call the BsModalRef.hide() method when the prompt (sweetalert) is closed. However, when the modal is closed using the ESC key or click-outside events provided by Boots ...

Is there a restriction on the amount of data that can be

I have provided the code snippet below for reference: <System.Web.Services.WebMethod()> _ Public Shared Function LinkedUSNs(ByVal usn As String, ByVal requester As String, ByVal reason As String, ByVal terminalip As String, ByVal strCon As Strin ...

What is the best way to handle multiple axios calls with pagination in a React application?

Discussing React Pagination and Handling Multiple Axios Calls In my current project, I am faced with the challenge of mapping through an array of numbers and making sequential API calls for each one. The API I'm working with returns paginated results ...

What is the best way to seamlessly incorporate a new line into the string saved in the AMP state?

I am exploring the world of Accelerated Mobile Pages and trying to enhance my skills. My current challenge involves adding a new line and some additional text content to a string stored in the amp-state when the user clicks a button. Here is what I have at ...

The Canvas element inside a Bootstrap modal is returning inaccurate mouse coordinates

I am currently troubleshooting an issue with a HTML5 canvas inside a Bootstrap modal. The canvas is designed to be a selection game where objects can be selected and manipulated. Everything works fine in the center of the 600x600px canvas, but there is an ...

Using JQuery in a Vue JS project without npm is not allowed

I'm attempting to include JQuery in my Vue JS project without relying on npm. Here's the approach I'm taking: ***custom-jquery.js*** import '../../public/js/jquery.min.js' export function customFunction(){ $(".element" ...

A guide to eliminating missing tags from HTML code using Asp.net

There have been instances where the HTML code we receive from certain websites does not have proper tag endings, causing issues with our UI. For example: <br /><p>hello the para start here </p> <p>some text and no ending tag As yo ...