Guide on attaching an event to every dynamically created element in JavaScript

I'm currently generating 'li' elements dynamically using a loop and running into issues when it comes to assigning events to each generated element. My goal is to assign an onclick event to every li element that is created.

Check out the code snippet below:


var notifications = [{
  "event": "It's your friend's Birthday. Wish him luck!!!",
  "view": "unread",
  "status": "read",
  "image": "<img src='cake.jpg' style='height:80px;width:80px'>"
}]

var ids = ["id1", "id2", "id3", "id4", "id5"];
var lis = new Array(10);
var i = 0;

for (i; i < notifications.length; i++) {
  lis[i] = document.createElement("li");
  var obj = document.createTextNode(notifications[i].event);
  lis[i].appendChild(obj);
  document.body.appendChild(lis[i]);
  lis[i].setAttribute('id', ids[i]);
  var x = document.getElementById(ids[i]);
  x.addEventListener("click", func('ids[i]'));
  document.body.appendChild(ids[i]);

}

function func(a) {
  document.getElementById(a).innerHTML = "hello";
}

There are also additional objects similar to the one above.

Answer №1

Consider using

x.addEventListener("click", func);

rather than

x.addEventListener("click", func());

When you use func(), the function is called and its return value is sent instead of passing the function itself.

Answer №2

One solution is to utilize the .bind method, which allows you to bind a value to an event listener. Instead of

x.addEventListener("click", func('ids[i])');
  1. By using this syntax, you are assigning the return value of func to the event listener.
  2. The string 'ids[i]' does not represent a variable, but rather a string literal.

To rectify this issue, make the following replacement:

x.addEventListener("click", func.bind(ids[i]));

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

What are the steps for loading JSON data into a select dropdown with the help of AJAX?

I am trying to create a dropdown list of schools using the select tag. Currently, I have hard coded values for the list, but I want to fetch the data from a RESTful service instead. Can someone please provide guidance on how to achieve this? <html& ...

The production build of Angular 2 with special effects amplification

I am currently working on an Angular 2 Beta 8 app that I need to bundle and minify for production deployment. Despite configuring the system to generate a Single File eXecutable (SFX) bundle, I am encountering issues with creating a minified version of the ...

Steps to display a video using a Jupyter widget in a Jupyter Notebook

Imagine I have a directory containing 4 video files (such as "movie1.mp4", "movie2.mp4" and so on). I aim to utilize ipywidgets to enable the user to choose which video they want to watch. Here's an example: import ipywidgets as wd from IPython.disp ...

Having trouble getting the convert-multiple-files npm package to function properly on an Elastic Beanstalk environment running Amazon Linux

Following a successful deployment, I encountered an issue with my file conversion script when attempting to convert files as outlined in the documentation. The script works flawlessly on both a local Windows 10 machine and Ubuntu 20.04 LTS. const { conv ...

What causes the element to load with a transparent appearance? And why is my JavaScript code overriding the hover effect on it?

My goal is to have an element fade out when clicked and then fade back in when its space is clicked again. I also want the opacity of the element to be 0.9 instead of 1 when visible. I've encountered two issues with my code. First, the hover selector ...

Issues with Jquery datatable causing column header to overlap the table header

I am facing an issue with my datatable as the table is not displaying correctly. Could someone advise me on how to troubleshoot and fix this problem? Below is the code snippet in question: $(tbName).dataTable({ "sScrollX": "100%", "sScro ...

Changing the class of a div in JavaScript from one class to another

On my HTML page, I have a div with a CSS class assigned to it. The goal is to switch the current class for another when a button is clicked. It's crucial that not a single CSS property within the class is altered - the entire class must be replaced en ...

Surround the image with horizontal links on each side

I am attempting to design a horizontal unordered list with an image positioned in the center of it. I am facing the challenge of not being able to insert the image directly within the unordered list. Is there a way to align the image in the center while ha ...

Is there a way to determine if a browser's Storage object is localStorage or sessionStorage in order to effectively handle static and dynamic secret keys within a client?

I have developed a customizable storage service where an example is getExpirableStorage(getSecureStorage(getLocalStorage() | getSessionStorage())) in typescript/javascript. When implementing getSecureStorage, I used a static cipher key to encrypt every ke ...

What is the best way to add a character within a YouTube JSON link?

Fetching json data from a link, the youtube format in the link is http:\/\/www.youtube.com\/watch?v=UVKsd8z6scw. However, I need to add the letter "v" in between this link to display it in an iframe. So, the modified link should appear as ht ...

Having difficulty accessing a PHP ajax post request

I've scoured every resource but can't seem to find a solution to this issue. I'm in the process of writing an ajax script, however, I am struggling to retrieve the correct value from the POST request. Here is the code I have so far: <t ...

I want to retrieve a complete HTML page using an AJAX request

I am trying to retrieve the content of a specific page, but encountering issues when using this function: function getResult() { var url="http://service.semanticproxy.com/processurl/ftfu27m3k66dvc3r43bzfneh/html/http://www.smallbiztechnology.c ...

Having trouble with Jquery Ajax call in IE8?

I have a dynamic data loading from the database, with each row containing links that perform various actions. Most of them work perfectly fine, but I've noticed an issue with the last one I added – it doesn't seem to be functioning properly on ...

Tap on the div nested within another div

Here is the scenario I am dealing with: <div id="main"> <div id="a"></div> <div id="b"></div> </div> On my website, element B is positioned below element A. How can I attach a click event only to those A elements t ...

Browser tries to interpret Javascript code as a file organization system

Encountering an issue while trying to load my website. When I open index.html in my browser, I receive a problem loading page message. This response is puzzling as it does not indicate a file loading error. Here's a snippet of the response: Firefox c ...

What is the best way to incorporate a new attribute into an array of JSON objects in React by leveraging function components and referencing another array?

Still learning the ropes of JavaScript and React. Currently facing a bit of a roadblock with the basic react/JavaScript syntax. Here's what I'm trying to accomplish: import axios from 'axios'; import React, { useState, useEffect, useMe ...

Tips for loading a webpage when a button is clicked with the help of jQuery AJAX and PHP:

Is it possible to dynamically load a page on button click, pass data to the new page using jQuery AJAX, and place the received value in an input field within the loaded page? Basically, the scenario is as follows: A button named "Something" triggers the l ...

error encountered in ajax contact form due to issue with select element

I'm experiencing an issue with my ajax contact form, where the input field and select element are not providing the expected results. This is the HTML Form Code (with "name" as the input and "iphone" as the select element) <div id="contact_form" ...

Tips on fetching the ID of the selected option using JavaScript without relying on jQuery

Looking to print the selected option ID using pure Javascript (not JQuery) for multiple select tags. If we have more than one select tag, how do we achieve this? <select onchange="showOptions(this)" id="my_select1"> <option value="a1" id="ida ...

`Month filter functionality optimized`

I have a flirty plugin installed on my website and it's working great except for one thing: I'd like the month category to be filtered in chronological order instead of alphabetically. Is there a way to achieve this? In simpler terms, how can I ...