The extent of a nameless function when used as a parameter

I am currently developing a straightforward application. Whenever a user hovers over an item in the list (li), the text color changes to green, and reverts back to black when the mouse moves away.

Is it possible to replace lis[i] with this keyword in the code snippet below within the anonymous function?

var lis = document.querySelectorAll('li');
var i = 0;
for(; i < lis.length; i++){

    lis[i].addEventListener('mouseover', function(){

    this.style.color = 'green';

    });
    lis[i].addEventListener('mouseout', function(){

    this.style.color ="black";  
    });
};

Answer №1

Once the callback function is triggered, the i variable will hold the value of lis.length because of the loop. This causes the value of lis[i] to become undefined.

A more effective approach would be to utilize the forEach function.

var lis = document.querySelectorAll('li');
lis.forEach(function (li) {
  li.addEventListener('mouseover', function (){
    li.style.color = 'green';
  });
  li.addEventListener('mouseout', function (){
    li.style.color = "black";  
  });
});
<ul>
  <li>First Item</li>
  <li>Second Item</li>
</ul>

Answer №2

When the function is called, the loop will have already finished its execution. Inside the function, there is a single i variable that always reflects its current value. Therefore, if you reference i within the function, it will show as lis.length.

There are workarounds to this issue. If you have access to ES2015 (potentially through a transpiler), you can do the following:

const lis = document.querySelectorAll('li');
for(let i = 0; i < lis.length; i++){

    lis[i].addEventListener('mouseover', () => lis[i].style.color = 'green');
    lis[i].addEventListener('mouseout', () => lis[i].style.color ="black");
};

This way, you create a distinct i for each iteration of the loop.

Alternatively, in older code, you can move the loop body to another function and pass i as a parameter. This approach achieves the same outcome of binding a unique variable for each event:

var lis = document.querySelectorAll('li');

var _loop = function _loop(i) {

    lis[i].addEventListener('mouseover', function () {
        return lis[i].style.color = 'green';
    });
    lis[i].addEventListener('mouseout', function () {
        return lis[i].style.color = "black";
    });
};

for (var i = 0; i < lis.length; i++) {
    _loop(i);
}

(this code is automatically generated by babel from the earlier ES2015 example)

Answer №3

To retrieve the current target, you can utilize the "e.srcElement" method as demonstrated below:

let elements = document.querySelectorAll('element');

for (let i = 0; i < elements.length; i++) {
  elements[i].addEventListener('click', function(e){
    e.srcElement.style.backgroundColor = 'blue';
  })
  elements[i].addEventListener('dblclick', function(e){
    e.srcElement.style.backgroundColor = 'white';
  })
}
<div>
  <element>First Element</element>
  <element>Second Element</element>
</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

Challenges arise with CSS alignment when adding d3.js charts to a webpage

I'm puzzled by the empty space that appears between the left column (highlighted in the image) and the header. This peculiar gap only seems to occur when the middle column is filled with a chart. I've scrutinized the code using Chrome Developer t ...

What are some effective ways to optimize a chat application and reduce the strain on the server?

I once created a Python app that allowed users to create chat rooms using a simple REST API server. The client would send requests to the server, which would then respond appropriately. These responses were received by a JavaScript client that continuous ...

What is the best way to conceal the button?

I'm working on a program that involves flipping cards and creating new ones using three components: App, CardEditor, and CardViewer. Within the CardEditor component, I am trying to implement a function that hides the button leading to CardViewer until ...

Exploring Next.js dynamic imports using object destructuring

import { UDFCompatibleDatafeed } from "./datafeeds/udf/src/udf-compatible-datafeed.js"; I'm facing a challenge in converting the above import to a dynamic import in Next.js. My attempt was as follows: const UDFCompatibleDatafeed = dynamic(( ...

The Font Awesome icons do not display offline

I'm having trouble using Font Awesome icons offline on my webpage. I've included the necessary code, but for some reason it's not working. Here is what I have: <html> <head> <title>font-awesome example</title> ...

Ways to efficiently populate HTML elements with JSON data

I am working on grasping the concept of functional programming. My understanding so far is that it involves encapsulating everything into functions and passing them around. For instance, in my current example, I am attempting to fetch data from a RESTApi a ...

Step-by-Step Guide for Attaching Table Legs

I believe that the four legs should be an integral part of the table, rather than just added on like an afterthought. What would be the best way to create new instances of legs and attach them in a way that makes the back legs look slightly smaller than t ...

extract keys and values from an array of objects

I would like assistance with removing any objects where the inspectionScheduleQuestionId is null using JS. How can we achieve this? Thank you. #data const data = [ { "id": 0, "inspectionScheduleQuestionId": 1, ...

Retrieving selected option value in React

I am currently using Material UI for my React application and I am encountering an issue with getting the value of a select form. Initially, I had success with the following code snippet: <select name="role" value={props.role} onChange={props.handleIn ...

My JavaScript if-else statement isn't functioning properly

I'm facing an issue with my if statement not functioning correctly when trying to validate non-numeric inputs for the weight variable upon submission. What could be causing this problem? submitBtn.onclick = function(){ var name = document.get ...

What is the method for creating a hovering triangle on a particular element?

My navigation bar consists of two parts. On the left side, there is a logo image, and on the right side, there are 4 list elements. I am attempting to make a triangle appear at the bottom of the element when hovered. I have floated the list to the right an ...

Forming a space between borders

I'm attempting to create a space within a div's border that can accommodate an image, much like so: Is there a method to achieve this using only CSS? The only solution I have found is: .box { background: url(img.png) bottom left; border ...

Guide to importing firebase-functions and firebase-admin using ES6 syntax for transpilation with Babel in Node 10

I've been working on my cloud functions in ES6 and using Babel to transpile them for the Node v10 environment. But, I've come across an odd issue. It seems that when I import firebase-functions like this: import functions from 'firebase-fu ...

Commitments when using a function as an argument

While I have a good understanding of how promises function, I often struggle when it comes to passing a function as a parameter: var promise = new Promise(function(resolve, reject) { // Perform asynchronous task ec2.describeInstances(function(err, ...

The POST request made using Postman shows an empty Node.js/Express req.body

Here is the current code snippet I am working with: var express = require('express'); var router = express.Router(); var db = require('../helpers/db'); var data = { "1": 127, "2": 236, "3": 348 } router.get('/', ...

What is the best way to continuously update CSS styles within a loop?

My goal is to create a function that will change the left position of a <div> element in a loop, making it appear as though it is moving. However, instead of smoothly transitioning, the element just jumps to its end position. function animateElement ...

What is the best way to align text in the center based on a specific portion of the content?

I'm working on an inline flex div where I want to create a unique effect using the words wrap and the div overflow. As the window is resized, some of the words in the sentence will disappear, altering the meaning. The width will determine the result: ...

Submit Form using Ajax - Update text in HTML element upon click

As I am working on developing a message system, I encountered an issue where the message content is not opening correctly in my template when clicking the "See" button. My intention is to implement an Ajax call that will replace the content with jQuery .te ...

There seems to be a connection issue between my Jquery and HTML, as they

I've hit a roadblock because my jQuery isn't connecting and I can't seem to figure out why. It's been stumping me for hours. Here is the HTML code snippet from exercise6.html: <!DOCTYPE html> <html lang="en> <h ...

Ways to verify if element has been loaded through AJAX request

I am trying to determine if an element has already been loaded. HTML <button>load</button> JS $(document).on('click','button',function () { $.ajax({ url: 'additional.html', context: document ...