Is it possible to retrieve the key value of the array element that triggered a function call?

I'm looking to streamline my webpage's code by reading an XML file that contains a variable number of objects. In my JavaScript code, I create an array to store each object and loop through the XML data to generate them.

As I iterate through the XML nodes to create objects and their functions (such as mouseover, onclick, etc.), I encounter an issue. I use the same index variable in these functions to access the current object's properties. However, when the function is triggered, the index variable is no longer within the correct range.

Is there a way for me to retrieve the key (index) value of the calling object?


for (index = 0; index < scenes.length; index += 1) {
    this.thumbs[index] = document.createElement('div');
    // set up more properties
    this.thumbs_image[index] = document.createElement('img');
    // more setup
    this.thumbs[index].onmouseover = function() {
        me.thumbs_image[index].src = scenes[index].attributes.getNamedItem("src").nodeValue;
        // THIS IS THE ISSUE - The index is incorrect when the function is executed.
    }
}

The code outside of the onmouseover function works fine, and if I hardcode the index inside onmouseover, it also works.

I've tried creating a separate function with the index passed as a parameter, but even when dynamically assigning the function, I still struggle with using the appropriate index:


this.thumb[index].onmouseover = myFunction(index);

function myFunction(i) {
    me.thumbs_image[i].src = scenes[i].attributes.getNamedItem("src").nodeValue;
}

Is there any way to obtain the key of the element calling onmouseover?

I'm hoping there's a simple solution that I might have overlooked. Any advice would be greatly appreciated!

Thank you!

Answer №1

Initial approach: start by replacing the following:

this.thumbs[index].onmouseover = function(){
  me.thumbs_image[index].src = scenes[index].attributes.getNamedItem("src").nodeValue;
}

with this:

this.thumbs[index].onmouseover = (function(i) {
  return function() {
    me.thumbs_image[index].src = scenes[index].attributes.getNamedItem("src").nodeValue;
  };
})(i);

The use of a function wrapper ensures that the value of the variable i is captured in a closure. This allows you to access the correct value when the handler is triggered, as opposed to an undefined variable i.

Alternative solution: Instead of directly interacting with elements like in the first solution, consider passing the event object to the event handler. For example:

this.thumbs[index].onmouseover = function(evt) {
  console.log(evt.target);
}

In this specific scenario, the second solution may be more appropriate. However, it is valuable to understand the concept presented in the first solution - avoiding direct dependency on loop counters and using function calls to capture values instead.

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

Update the browser value using AJAX without the need to refresh the page

After retrieving a value from an XML file using ajax jquery, I encountered an issue. When I change the value in my XML file, it does not automatically update in the browser. <?xml version="1.0"?> <count><number>5</number></count ...

Using PHP to beautify JSON data

I'm currently working on generating JSON output for a specific JavaScript application, but I'm encountering a formatting issue that the script is not recognizing. Here's how I've structured my JSON so far: // setting up the feed $feed ...

Generating identical circles using PointsMaterial and CircleGeometry

My goal is to generate circles using two different methods: By utilizing a circle sprite and drawing it with Points and PointsMaterial Using basic circle buffer geometries Unfortunately, I am facing challenges trying to align them due to the size discrep ...

Fluctuate the window.location with jQuery or javascript

My goal is to create a functionality where clicking an image will toggle the window.location url between '#' and '#footer'. The current code I have for this is: <script> function clickarrow(){ var rd=Math.floor(Math.random() ...

Direct a flow to an unknown destination

What I am trying to achieve is writing a stream of data to nowhere without interrupting it. The following code snippet writes the data to a file, which maintains the connection while the stream is active. request .get(href) .on('response', func ...

How can you efficiently load the materials for a THREE.BoxGeometry using THREE.LoadingManager()?

I am looking to enhance the image quality of a geometry after user interaction by initially loading low-resolution assets and then switching to high-resolution assets when the user interacts with it. When using the following standard code: var materials = ...

Having trouble retrieving Bengali-language data from the server using jQuery AJAX

I am facing an issue where I am unable to fetch data in Bengali language from the server using ajax. Strangely, the data retrieved from the server is getting replaced by some unknown characters. However, if I directly retrieve the data without using ajax, ...

I am attempting to build a party planning website but I am encountering an issue where the output is not generating properly. Whenever I click on the submit button, the information I input

I am struggling to create a party planner website and encountering issues with the output. Whenever I click on the submit button, the form just clears out without any feedback or result. Here is what the expected output should be: Validate event date 1: ...

Leveraging Vue properties within CSS styling

I am looking to utilize Vue data/prop variables within the <style> tag located at the bottom of my component. For example, suppose I have a component structured like this: <template> <div class="cl"></div> </template> < ...

When a new element is introduced, onmouseenter feature assigns a unique dynamic function variable

I am incorporating elements generated by Javascript using a for loop. My goal is to pass different variables to a function for each element. Check out my code snippet: var thumbnail_box = document.createElement("div"); thumbnail_box.onmouseenter = functi ...

Toggle between classes by clicking on the next or back button

Looking to create a multi-step form where the initial step is visible while the rest are hidden using the "hide" class. I want to toggle visibility of each step with Next and Back buttons, displaying only one step at a time. Can someone assist with this? ...

How to achieve a seamless iframe effect using CSS

With the introduction of new HTML5 iframe attributes, there are now more options available. One such attribute is the seamless attribute, which has the ability to: Create an iframe that appears to be seamlessly integrated into the containing document. ...

What could be causing my component to not recognize a change in props?

I've been following the steps correctly, but I can't seem to figure out what's missing. Any assistance would be greatly appreciated. Thank you. function Application() { let pageData = "data saved in the database"; return ( <div ...

Saving a variable's value using Knockout loop within an HTML document

As a newcomer to KO, I have been utilizing the following code in my HTML file to print a specific value: <!-- ko foreach: { data: JSON.parse($parent.options), as: 'option' } --> <!-- ko if: option.label === 'AAA' || option. ...

notify a designated channel when ready for launch

I'm currently attempting to figure out how to send a message to a channel when the Discord bot is launched. I've experimented with this code: client.on('message', (message) => { client.on('ready', () => { channel = cli ...

Toggle the mute and unmute feature for a participant in an AWS Chime meeting

Hello everyone! I'm looking for details on the AWS Chime SDK (amazon-chime-sdk-js). Is it possible with the Amazon Chime SDK for 3 participants (Anna, John, and Lenny) in a meeting room to have Anna ignore Lenny's microphone and only hear John, ...

Learn how to incorporate a click event with the <nuxt-img> component in Vue

I am encountering an issue in my vue-app where I need to make a <nuxt-img /> clickable. I attempted to achieve this by using the following code: <nuxt-img :src="image.src" @click="isClickable ? doSomeStuff : null" /> Howeve ...

How can Redux help persist input value through re-rendering?

Handling Input Value Persistence in Redux despite Re-rendering? I am currently able to store and save input values, but only the data from one step ago. For example, when I click on the second input field, it displays the value from the first input fiel ...

Making adjustments to a row in the free jqGrid is a breeze with the ability

Using free jqGrid 4.12.1, I aim to incorporate functionality for adding, editing, and deleting rows in the grid with server-side calls for each operation. Below is the implementation of editurl and 'actions' formatter, { name: "actions", wi ...

What is the purpose of requiring the explicit invocation of app.listen(port) to enable express-ws to function properly?

I've recently started exploring NodeJS Express and came across the official tutorial from express-ws for setting up websockets in a simple project generated using npx express-generator. While following the tutorial, I noticed that in the app.js file, ...