How can I attach events to newly generated elements without using jQuery?

If I want to dynamically add a form to my webpage (through AJAX or other JavaScript methods), how can I attach event listeners to these elements before they actually exist on the page?

When using jQuery, it's simple to bind the events to a parent element like this:

$(document).on('blur', 'input', function() {...})

However, I'm not sure how to achieve this with plain JavaScript, as addEventListener requires direct application to the element itself and doesn't allow specifying a parent element for event propagation. Am I correct in thinking this way?

Answer №1

My approach to delegation is straightforward. It involves binding events to the top parent element for efficiency and speed. When delegating an event, it's best to target a specific div to avoid conflicts. By comparing event.target with your desired target element, you can successfully trigger your callback function.

document.addEventListener('focus', function(event){

  if(event.target.tagName == 'INPUT'){
      onFocusApply(this, arguments);
  }

}, true);

function onFocusApply(event){
   
  // console.log(event); // event
  console.log(event.target.value);
  
}
<input type="text"/>
<input type="text"/>
<input type="number"/>

Answer №2

If you're looking to add event listeners in vanilla JavaScript, it's actually quite simple. However, it's worth noting that focus/blur events behave a bit differently compared to most events. To ensure they work properly, you'll need to add a tabindex to your container element (for more details, check out this link).

document.querySelector(".container").addEventListener("blur", function(e){ 
   if(e.target.tagName == "input"){
      // do something
   }
}, false);

For a demonstration of this in action, take a look at this JSFiddle example (Note: remember to have your console open to see the output).

Answer №3

const registerEvent = (event,elementId,callback) =>{
document.addEventListener(event,e=> {
      if (e.target !== e.currentTarget) {
      if(e.target.id==elementId){
      callback();
      }
      }
      e.stopPropagation();
  },false);
  }

Example usage:

registerEvent("click","myElement",function(){});

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

Updating a value in Expressjs variable is not working as expected

In the code snippet below, I have declared a variable called sumOfRevenue. I assigned it a value of 10 in the router, but when I try to print its value, it comes out blank. Can you please help me understand why it's not showing as 10? Please review t ...

What is the best way to transfer the value of a radio button, retrieved from a database, to a textbox?

Greetings, I am trying to figure out how to pass the value of a radio button to a textbox using jQuery and PHP. The radio buttons are generated dynamically based on rows from my database, so I set the row ID as the ID for each radio button. However, the co ...

Is there a way to redirect the user to a different page without refreshing the page during navigation?

Utilizing javascript, ajax, and jquery to dynamically load content from PHP files without refreshing the page has been a successful venture. However, I am facing a challenge in creating a hyperlink within one of the loaded contents that redirects the user ...

Capturing an error within an asynchronous callback function

I am utilizing a callback function to asynchronously set some IPs in a Redis database. My goal is to catch any errors that occur and pass them to my error handling middleware in Express. To purposely create an error, I have generated one within the selec ...

Is there a glitch in JavaScript when comparing dates?

What's wrong with this code? function test() { var start = new Date(2012, 3, 31, 19, 0, 0); // Start: 3/31/2012 7:00 PM var end = new Date(2012, 4, 1, 1, 0, 0); // End: 4/01/2012 1:00 AM if (end < start) console.log("oops ...

Storing Form Input in Browser's Local Memory

I am currently working on a form section where individuals can input their email addresses. However, I have encountered a couple of issues: (1) After submitting an email address, the page refreshes. While I understand that this is inevitable without usin ...

Refreshing a webpage following an AJAX call

Whenever I make a post request to an API, I receive a response. However, even though the data is saved when I hit the API, I have to manually refresh my blade.php page to see the newly added data. Is there a way to automatically update my blade with the ...

Group By feature in AngularJS

Hey there, I'm trying to display a table from the code provided below. The issue I'm facing is with grouping by name. Here's how I want the view to appear: Shareholder | Preferred Stock | Common Stock | Options | Percentage | |----------- ...

Display input field in AngularJS when radio button is selected

My JavaScript array looks like this: $scope.quantityMachines = [ { 'snippet' : 'One' }, { 'snippet' : 'Two' }, { 'snippet' : 'Three or more', 'extraField' : true }, { ' ...

Combining NodeJS with PHP: A Seamless Integration

They say NodeJS is perfect for creating real-time chat applications and I'm eager to add a chat feature to my website. Right now, I have the design ready and need to work on the back-end code. However, when I use socket.io + express, things don' ...

Angular 1.5 component using HTTP GET

Trying to utilize a 1.5 component with AngularJS has presented some challenges for me. I have a service that fetches my JSON file using $HTTP and returns a promise. In the controller of my component, I resolve the promise and assign it to a value using thi ...

Creating a Drop-Down Button Using HTML, CSS, and JavaScript

I am currently working with the following code: <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=PT+Sans ...

What is the method for setting the doctype to HTML in JavaScript or React?

I created a canvas with a height equal to window.innerHeight, but unexpectedly it seems to have 100% screen height plus an extra 4 pixels coming from somewhere. I came across a solution suggesting that I need to declare doctype html, but I'm unsure ho ...

Looking for a method to incorporate an onclick function into a column for renderCell within the MUI Datagrid. Any suggestions?

I'm currently developing a react application and utilizing the MUI Datagrid to present some data. I have incorporated a rendercell to insert an edit icon which should trigger a pop-up modal when clicked. Below is the column setup. export const specifi ...

execute action after a specific point in time in the video is reached

How can I hide a div after a video has been playing for a certain amount of time? The code provided below seems like it should work in theory, but is currently not doing so. Any suggestions on how to fix this issue would be greatly appreciated! <body ...

Add a fresh column in the table that includes modified values from an existing column, affected by a multiplication factor provided through a text input

I'm currently working on a Laravel website where I have a pricing table sourced from a database. The Retail Price column in this table serves as the base for calculating and populating a Discount Price column using a multiplier specified in a text inp ...

What is the process of substituting types in typescript?

Imagine I have the following: type Person = { name: string hobbies: Array<string> } and then this: const people: Array<Person> = [{name: "rich", age: 28}] How can I add an age AND replace hobbies with a different type (Array< ...

Encountering a CORS issue when utilizing Stripe with various servers while navigating with a Router

I have a router that utilizes Router.express(). The backend operates on port 5000, while the frontend runs on port 3000. Within the frontend folder, there is a button with a fetch request (http://localhost:5000/create-checkout-session). In the backend, the ...

What is the best way to remove specific items from an AngularJS ng-repeat loop?

Is there a way to filter out certain items in an ng-repeat loop? For instance, consider the following simplified code snippet: <div class="row" data-ng-repeat="entry in data.feed.entry | orderBy:'gsx$timestamp.$t':true"> {{entry.gsx$jobID ...

How to utilize the index in a foreach loop as a variable in JavaScript

I am facing an issue with using the index of a forEach loop to access an array index in my code. It seems to work when I use a number directly, but not when I try to use the index variable. Any suggestions or insights on how to resolve this? let post ...