I wanna make a dynamic effect with CSS
& JS
and HR HTML
elements: the idea is making 4 lines horizontally like that:
And making it dynamic by adding an input of type range and making them grow & shrink at width based on the value of input range!
What I've tried so far:
document
.querySelector('input[type="range"]')
.addEventListener("input", (e) => {
document.querySelectorAll(".line").forEach((line) => {
line.style.width = line.offsetWidth + 10 + "px";
const marginOnLeft = window
.getComputedStyle(line)
.getPropertyValue("margin-left")
.slice(0, -2); //remove "px"
line.style.marginLeft =
Number(marginOnLeft) + 100 / Number(marginOnLeft) + "px";
});
});
.lines {
position: relative;
}
.line {
position: absolute;
}
hr {
background-color: black;
border-radius: 5px;
}
.line1 {
width: 500px;
height: 3px;
margin-left: 0;
margin-top: 5px;
}
.line2 {
width: 400px;
height: 6px;
margin-left: 50;
margin-top: 5px;
}
.line3 {
width: 300px;
height: 8px;
margin-left: 100;
margin-top: 5px;
}
.line4 {
width: 200px;
height: 10px;
margin-left: 150;
}
input[type="range"] {
margin-top: 70px;
}
<div class="lines">
<hr class="line line1" />
<hr class="line line2" />
<hr class="line line3" />
<hr class="line line4" />
</div>
<div>
<input type="range" name="" id="" value="10" />
</div>
How can I track if the user's input range
increase or decreases; based on its value all horizontal lines will be dynamically become wider or narrower at the width! even more, I would the margin-left
also be dynamically increase or decreases depending on the input range value
, Am I doing it right or maybe using CSS variables
; any suggestions are welcome and more appreciated!
Make some small changes -
var oldValue = 10;
document
.querySelector('input[type="range"]')
.addEventListener("input", (e) => {
document.querySelectorAll(".line").forEach((line) => {
if(parseInt(e.target.value) > oldValue){
line.style.width = parseInt(line.offsetWidth) + parseInt(e.target.value) + "px";
}else{
line.style.width = parseInt(line.offsetWidth) - parseInt(e.target.value) + "px";
}
});
oldValue = e.target.value;
});
remove from css
.line {
position: absolute;
}
Update css
.line2 {
width: 400px;
height: 6px;
position: absolute;
top: -1px;
left:50px;
background:green;
}
.line3 {
width: 300px;
height: 8px;
position: absolute;
top: -2px;
left:100px;
background:green;
}
.line4 {
width: 200px;
height: 10px;
position: absolute;
top: -3px;
left:150px;
background:green;
}
click JSfiddle to see