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
}