I want to create a slider (input tag) that receives an input as the user slides it. The value gets recorded and out of 100 rectangles already created ‘value’ of the 100 get colored. If I take the slier to 76, 76 rectangles should be shaded and all others should be white.
const slider = document.querySelector('.slider');
const carsContainer = document.querySelector('.cars-container');
const cars = carsContainer.querySelectorAll('.car');
slider.addEventListener('input', function () {
const sliderValue = slider.value;
console.log(sliderValue);
for (let i = 0; i < sliderValue; i++) {
cars[i].style.backgroundcolor = 'yellow';
}
});
.slider-container {
width: 80%;
margin: 0 auto;
}
.slider {
width: 100%;
}
.cars-container {
display: grid;
grid-template-columns: repeat(10, 1fr);
grid-template-rows: repeat(10, 1fr);
gap: 1rem;
margin: 0 auto;
width: 80%;
}
.car {
--size: 6.2rem;
width: var(--size);
height: calc(var(--size) / 2);
margin: 0 auto;
background-color: #ccc;
border-radius: 1rem;
transition: transform 0.3s ease-in-out;
}
<div class="slider-container">
<input type="range" min="1" max="100" value="5" class="slider" />
</div>
<div class="cars-container">
<!-- 01 -->
<div class="car"></div>
.
.
.
<!-- 100 -->
<div class="car"></div>
</div>
2
Answers
When you lower the slider, you need to change all the rest of the rectangles back to white, otherwise they’ll keep their yellow color from before.
You also have a typo in
backgroundColor
; case is significant.Here’s a CSS solution which doesn’t require re-toggling inline
background-color
:(Note that
:has()
is not very well supported yet)Try it: