Issue
My Problem:
Hey guys. I just have a question regarding changing CSS properties using JavaScript. I want to use an equation I wrote in JavaScript to change the value of a CSS property.
My goal is for the brightness of each element to change based on its distance (in terms of its "zIndex") from the currently selected item.
What I've Tried:
I've tried declaring variables in CSS, such as "var(--brightness)" for the filter property, but I don't really understand it that well yet so I can't get it to work and I don't even know if that's the correct strategy to use in this case.
I want the selected item's brightness to be 100% and increase the brightness by 30% for every element next to it until it hits the end.
Is anyone able to help me figure out what I'm doing wrong?
My Code:
HTML:
<body>
<div class="container">
<div class="div-items">
<img class="current-item" src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/SNice.svg/1200px-SNice.svg.png">
<img class="item" src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/SNice.svg/1200px-SNice.svg.png">
<img class="item" src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/SNice.svg/1200px-SNice.svg.png">
<img class="item" src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/SNice.svg/1200px-SNice.svg.png">
<img class="item" src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/SNice.svg/1200px-SNice.svg.png">
</div>
</div>
</body>
CSS:
:root {
--brightness: 1;
}
body {
height: 100%;
}
.container {
align-items: center;
justify-content: center;
height: 100%;
background-color: white;
width: 100%;
}
.item {
position: fixed;
left: -37px;
top: -37px;
cursor: pointer;
filter: var(--brightness);
transition: filter 0.5s;
}
.current-item {
transition: filter 0.5s;
}
JavaScript:
var items = document.getElementsByClassName('item');
for (i = 0; i < items.length; i++) {
var itemClass = items[i].classList
var currentItemIndex = 0;
if (itemClass.contains('current-item')) { // If it is the current item, then this:
items[i].style.filter = 'brightness(1)'; // Change brightness to 100%
currentItemIndex = i; // Change current item to this position
} else if (!itemClass.contains('current-item')) { // If it is not the current item, then this:
var brightness = (100 + (Math.abs(currentItemIndex - i) * 30)) / 100; // Increase by 30% for every position away from current item and assign the float to the variable
items[i].style.setProperty('--brightness', brightness); // Change the value of "--brightness" to the float assigned to "brightness"
}
}
Solution
There’s no need for the CSS variable. You can directly set the value of the filter property:
items[i].filter = "brightness(" + brightness + "%)”;
where the variable brightness is the result of your equation.
Answered By - Pablo Correa
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.