What DOM event allows for a constant triggering as I drag a range slider?

Viewed 35

I currently have a slider and a box next to it, in which I would like to display the current value of the slider. I want the value in the box to continuously change as I drag the slider from 0 - 100. Which DOM event best describes this sort of event? Currently I have it on click off so it updates the value in the box after I finish moving the slider.

let text1 = document.getElementById("sliderText1");
let slider1 = document.getElementById("slider1");
text1.textContent = slider1.value + "%";
slider1.addEventListener("mouseup",function(){
  text1.textContent = slider1.value + "%"
});
<!DOCTYPE HTML>
<html>
<head>
  <title></title>
</head>
<body>
  <div style="float:left";>
    <input type="range" id="slider1" min="0"        max="100" value="50"> 
  </div>
  <div style = "float:left;">
    <p id = "sliderText1" style = "margin-top:      2px; margin-left: 2px; border-style:          solid"></p>
  </div> 
<script src="script.js"></script>
</body>
</html>

2 Answers

You can use the mousemove event, that should work.

Here is the MDN documentation on the event https://developer.mozilla.org/en-US/docs/Web/API/Element/mousemove_event

let text1 = document.getElementById("sliderText1");
let slider1 = document.getElementById("slider1");
text1.textContent = slider1.value + "%";
slider1.addEventListener("mousemove",function(e){
  text1.textContent = slider1.value + "%"
});
<!DOCTYPE HTML>
<html>
<head>
  <title></title>
</head>
<body>
  <div style="float:left";>
    <input type="range" id="slider1" min="0"        max="100" value="50"> 
  </div>
  <div style = "float:left;">
    <p id = "sliderText1" style = "margin-top:      2px; margin-left: 2px; border-style:          solid"></p>
  </div> 
<script src="script.js"></script>
</body>
</html>

You can do a combination of mouseup and mousedown along with the setInterval global function.

mousedown event only executes once after clicking the mouse, hence the approach with setInterval.

Run the setInterval on mousedown and cancel it on mouseup.

let text1 = document.getElementById("sliderText1");
let slider1 = document.getElementById("slider1");
text1.textContent = slider1.value + "%";
let intervalId;
slider1.addEventListener("mouseup", function() {
  clearInterval(intervalId);
  text1.textContent = slider1.value + "%"

});

slider1.addEventListener("mousedown", function() {
  intervalId = setInterval(() => {
    console.log('mousedown')
  }, 100)
});
<!DOCTYPE HTML>
<html>

<head>
  <title></title>
</head>

<body>
  <div style="float:left" ;>
    <input type="range" id="slider1" min="0" max="100" value="50">
  </div>
  <div style="float:left;">
    <p id="sliderText1" style="margin-top:      2px; margin-left: 2px; border-style:          solid"></p>
  </div>
  <script src="script.js"></script>
</body>

</html>

Related