Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

190
Visualizações
How to Update a Variable that Relies on Code After It? (JavaScript)

My Problem:

Hey everyone. I'm trying to write some code that changes the brightness of an element based on how far away it is from the current item. Everything runs according to plan, however, as it moves down the list all of the items before the current item begin to return "NaN" as their value. This makes sense, as the "currentItemIndex" variable is only given a value once it finds the current item's position, so there's no value for the "currentItemIndex" until it reaches the current item within the list.

What I've Tried:

I've tried declaring the "currentItemIndex" variable before it searches for the current item, giving it either a value of 0 to start or an empty string. The starting value of 0 results in the "currentItemIndex" staying at 0 no matter what, and the empty string just produces the same result as when there was no variable declared there in the first place.

I'm not sure how to get the "currentItemIndex" before searching for the current item and not have it affect the variable when it checks for the current item. Is anyone able to help me out?

My Code:

JavaScript:

var items = document.getElementsByClassName('item'); // Gets all of the items

for (i = 0; i < items.length; i++) { // For each of the items, this:
            
    var itemClass = items[i].classList // Get class of the item

    if (itemClass.contains('current-item')) { // If it is the current item, this:

        var currentItemIndex = i; // Set the current item's position to the target's position
                
    }
        
    var brightness = (100 + (Math.abs(currentItemIndex - i) * 50)); // Calculate how much the brightness should change based on the target's distance from the current item
    items[i].style.filter = 'brightness(' + brightness + '%)'; // Apply that brightness to the target

}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You'll need to find the currentItemIndex first, then do the loop setting the brightness:

const items = document.getElementsByClassName("item"); // Gets all of the items

let currentItemIndex;
for (let i = 0; i < items.length; i++) { // For each of the items, this:
    const itemClass = items[i].classList // Get class of the item
    if (itemClass.contains("current-item")) { // If it is the current item, this:
        currentItemIndex = i; // Set the current item"s position to the target"s position
        break;
    }
}

for (let i = 0; i < items.length; i++) { // For each of the items, this:
    const brightness = (100 + (Math.abs(currentItemIndex - i) * 50)); // Calculate how much the brightness should change based on the target"s distance from the current item
    items[i].style.filter = "brightness(" + brightness + "%)"; // Apply that brightness to the target
}

(With more context, it may be that there's a more concise way to find the index of that item [the first for loop], but the above works and it's simple.)


Side note: I added a declaration for i, so the code isn't relying on what I call The Horror of Implicit Globals. I strongly recommend using strict mode, so that's the error it always should have been.

about 4 years ago · Juan Pablo Isaza Relatório

0

You need to break the problem down into two steps:

  1. find the index of the current item
  2. calculate and set the brightness for every item
// get all of the items as an array
let items = Array.from(document.getElementsByClassName('item'));

// 1. find the index of the current item
let currentItemIndex = items.findIndex(item => items.classList.contains('current-item'));

// 2. calculate and set the brightness for every item
items.forEach((item, i) => {
    let brightness = (100 + (Math.abs(currentItemIndex - i) * 50));
    item.style.filter = `brightness(${brightness}%)`;
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda