Creating distinctive identifiers for individual function parameters in JavaScript using addEventListener

I am working on a for loop that dynamically generates elements within a div. Each element should trigger the same function, but with a unique ID.

for(var i = 0; i < 10; i++)
{
    var p = document.createElement("p");
    
    var t = document.createTextNode("asdf");
    p.appendChild(t);
    
    p.addEventListener("click", function(e){popup(e, i);}, false);
    
    document.getElementById("someDiv").appendChild(p);
}

Let's assume the function is:

function popup(e, id)
{
    //do stuff with the mouse event and get data according to the id
}

Therefore, I require the mouse event object to work properly.

Currently, every click results in the function being called with the same ID parameter (always sending 10 as the ID, although the mouse event functions correctly).

Any suggestions or insights would be highly appreciated!

Answer №1

The reason for the issue is that a closure is being created which holds onto the final value of i from the for loop. To resolve this, you should modify the following line:

p.addEventListener("click", function(e){popup(e, i);}, false);

To address this issue, start by defining a new function:

function generateFunc(i) {
    return function(e) {popup(e, i); }
}

Then update the line to:

p.addEventListener("click", generateFunc(i), false);

Refer to this post for further insights on this technique.

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

jQuery Does Not Iterate Through Arrays

I am encountering an issue where I am trying to populate an array with images and then pass them to a variable called $image. However, when I attempt to iterate over this array, the same item is being alerted three times. Here is the problematic code snip ...

What is the best way to choose all elements that fall between two specific elements?

Looking to grab content situated between two specific elements within an HTML structure. The HTML snippet in question is as follows... <h2>This is firsty</h2> <p>Some para</p> <ul> <li>list items</li> <li&g ...

Dynamic animations with RaphaelJS - Creating animated connections

I recently came across a similar project here: My current project involves animating boxes by clicking a button. While I am able to move the boxes around smoothly during animation, the issue is that the connections between them do not move along. Is there ...

What steps do I need to take to create npm packages specifically for react-native development?

Which programming languages are essential for creating npm packages that work on both android and ios platforms in react-native development? Can you suggest any helpful documentation or blogs for developing npm packages that support ...

Is there a way to link code and unit testing directly to npm test?

Is there a method to conduct unit testing in real-time on my server without having to create temporary files? I am looking for a way to supply both the code to be tested and the corresponding unit test to npm test. The information provided in the npm test ...

Error encountered: jQuery AJAX JSON request failed to be caught

While my WordPress AJAX process is successful, a peculiar error keeps popping up in Chrome Devtools: Uncaught TypeError: Cannot read property 'vehicle' of undefined. It's puzzling, as the parsed JSON data seems to be in the correct object fo ...

Finding the source of the err.kind expression in the MERN stack: Unraveling the mystery

Recently, I've been delving into the world of MERN stack development and came across an interesting technique for Error Handling in a tutorial. The tutorial showcased various expressions that can be used to identify different types of errors being thr ...

"Enhance search functionality by integrating live search results with clickable hyperlinks

I am currently working on implementing a live search feature in Laravel 7. Everything is functioning correctly, however, I am facing an issue where I am unable to add a (href a tag) to the result list. The results are being displayed in a select option usi ...

Please insert a decimal point and thousand separator into the text field

I'm trying to incorporate thousand separators and decimal points into my text box. Additionally, I have implemented the following directive: .directive('format', function ($filter) { 'use strict'; return { requir ...

What distinguishes defining a function through a prototype versus as a class property?

Check out this code snippet: Apple defines its function using a prototype. Banana defines its function using a class property. var Apple = function(){} Apple.prototype.say = function(){ console.debug('HelloWorld'); } var Banana = functio ...

Comparing Optimistic Updates and Tag Invalidation in RTK Query

I found a basic code example from the RTK query documentation: updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({ query: ({ id, ...patch }) => ({ url: `posts/${id}`, method: 'PUT', ...

Tips on displaying the appropriate object value in a text field based on the selection from a dropdown menu

In my Ruby on Rails form, I have a dropdown menu with various category names: <td> <div class="div1"> <%= f.collection_select(:category_id, Category.all, :name, id: 'category_select', :include_blank => & ...

Unlocking the Secrets: Expert Methods to Obtain Assets through HttpClient in Angular

After researching similar inquiries, such as the response provided in this thread, it seems that downloading or reading files from the assets directory can be accomplished easily by utilizing the get method of the HttpClient. For instance, if I have a Down ...

What is the best way to set the keyframes CSS value for an element to 0%?

Would like to create a progress indicator div using CSS animations? Check out the JSBin link provided. The desired behavior is to have the div width increase from 30% to 100% when the user clicks on stage3 after stage1, rather than starting from 0%. Althou ...

Error message displaying "Invalid ID attribute in HTML 5 input"

On my website, I have a page with multiple items, each containing an HTML5 input field. Whenever a user changes the value of the input, it triggers an AJAX call to the server. The server then responds with JSON data, including an array of items that have ...

Implementing the loading of a Struts 2 action with jquery in javascript

Looking to refresh a specific div using JavaScript with jQuery to target the div and a Struts action that loads the content. Can anyone offer advice on how to achieve this? The challenge lies in utilizing JavaScript and jQuery for this task. Best regards ...

What is the best way to display two tables side by side in a Vue component?

I am working on a vue application with a photo collection feature. My goal is to display the photos in two tables per row, iterating through the entire collection. Here's an example of what I'm aiming for: <row> &l ...

What steps are involved in a server utilizing Next.js to create a complete document for transmission to the client?

Understanding Next.js has been quite challenging for me. I am struggling to grasp how it operates on the server and how the server is able to implement server side rendering with the files generated by Next.js during the build process. I have a good under ...

Unable to locate item by its identification number

Search for results in the index and return them. Method: async fetchIndex(req,res){ const userResults = await Usuario.find(); res.json(userResults); }, Route: routes.get('/api/usuarios', Usuario.fetchIndex); Having trouble ...

Creating a column for dates using the js-xlsx library

After multiple attempts using js-xlsx, I have encountered an issue when trying to write a XLSX file with a Date column. Whenever I open the file in Excel 2010, the date is displayed as the number of days from a specific origin rather than in the desired fo ...