JavaScript incorporates input range sliding, causing a freeze when the mouse slides rapidly

Currently working on a custom slider and encountering an issue. When quickly moving the mouse outside the slider's range horizontally, exceeding its width, the slider doesn't smoothly transition to minimum or maximum values. Instead, there seems to be a pause. Is there a way to fix this and achieve a seamless slide?

Caton effect https://i.stack.imgur.com/wLFQq.gif

 const elWrap = document.getElementById('wrap');
  const elProgress = document.getElementById('progress');

  function onMouseMove(event) {
    const {clientX} = event
    const {left, right} = elWrap.getBoundingClientRect()

    // is the mouse inside the wrap?
    if (clientX < left || clientX > right) return

    // set progress width
    elProgress.style.width = `${(clientX - left) / elWrap.offsetWidth * 100}%`
  }

  // slider mousedown events
  elWrap.addEventListener('mousedown', function () {
    window.addEventListener('mousemove', onMouseMove);
    window.addEventListener('mouseup', function () {
      window.removeEventListener('mousemove', onMouseMove);
    }, {once: true});
  });
.x {
    padding: 128px;
  }

  #wrap {
    border-radius: 999px;
    width: 320px;
    height: 12px;
    background-color: #ccc;
    cursor: pointer;
  }

  #progress {
    height: 12px;
    width: 50%;
    border-radius: 999px;
    background-color: blue;
  }
<div class="x">
  <div id="wrap">
    <div id="progress"></div>
  </div>
</div>

Answer №1

Issue

When the mouse moves out of the specified range for the mousemove event, there is a line of code that ignores such events:

if (clientX < left || clientX > right) return

Resolution

Dealing with out-of-range events

if (clientX < left) {
  elProgress.style.width = `${0}%`;
} else if (clientX > right) {
  elProgress.style.width = `${100}%`;
} else {
  elProgress.style.width = `${((clientX - left) / elWrap.offsetWidth) * 100}%`;
}

const elWrap = document.getElementById('wrap');
const elProgress = document.getElementById('progress');

function handleMouseMove(event) {
  const {
    clientX
  } = event
  const {
    left,
    right
  } = elWrap.getBoundingClientRect()

  if (clientX < left) {
    elProgress.style.width = `${0}%`
  } else if (clientX > right) {
    elProgress.style.width = `${100}%`
  } else {
    elProgress.style.width = `${(clientX - left) / elWrap.offsetWidth * 100}%`
  }
}

// Slider mouse down events
elWrap.addEventListener('mousedown', function() {
  window.addEventListener('mousemove', handleMouseMove);
  window.addEventListener('mouseup', function() {
    window.removeEventListener('mousemove', handleMouseMove);
  }, {
    once: true
  });
});
.x {
  padding: 128px;
}

#wrap {
  border-radius: 999px;
  width: 320px;
  height: 12px;
  background-color: #ccc;
  cursor: pointer;
}

#progress {
  height: 12px;
  width: 50%;
  border-radius: 999px;
  background-color: blue;
}
<div class="x">
  <div id="wrap">
    <div id="progress"></div>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can a website built on Express.js be optimized for SEO?

Would pages created with the traditional route structure provided by Express (e.g. ) appear on Google's Search Engine Results Page as they would for a Wordpress blog or PHP website using a similar path structure? ...

Creating dynamic and engaging animations for components using ReactCSSTransitionGroup

I'm currently attempting to add animation to a modal that appears when a button is clicked using ReactCSSTransitionGroup. The modal is showing up on button click, however, there is no transition effect. My render method is set up like this: render() ...

Combining and adding together numerous objects within an array using JavaScript

I'm looking to combine two objects into a single total object and calculate the percentage change between the two values. I'm encountering some difficulties while trying to implement this logic, especially since the data is dynamic and there coul ...

I desire to incorporate a subtle fading effect into the script

I have written the script code and now I am looking to add a fade effect to it. Can anyone guide me on how to achieve this? Your help is much appreciated! ※I used an online translator as English is not my native language. Please bear with any awkward ph ...

Maximizing the width of navbar elements with Bootstrap 3

I am currently working on building a webpage with bootstrap3, but I have encountered an issue with the navigation bar. I would like the navigation links ("Web Design", "Development", "Photography", "Blog") to be evenly spaced out within the horizontal na ...

What is causing the input boxes to exceed their container boundaries so drastically?

My plan was to organize 4 input text boxes in 4 equal columns on a single row of the form. Using Bootstrap's grid column classes, I set col--3 for medium and large screens for those four inputs. For small and extra-small sizes, I designated them as co ...

Error: The variable "email" is not defined

Hey there, I could really use some assistance as a struggling developer. I've been at it all day trying to resolve this issue with no luck. It should be a simple task of posting from my AddUsers class and storing it in my SQL database. The state upda ...

Encountering issues with the functionality of my Bootstrap navbar

After diving into the world of bootstrap, I encountered some challenges with the navigation bar in mobile view. Despite adding a navbar and a toggle button, it doesn't seem to be functioning correctly. Following tutorials and examples meticulously, bu ...

Exploring AngularJS capabilities: Retrieving data and headers from an HttpResponse

Currently, I have a REST API developed using Spring Boot. In the frontend, AngularJS 1.5 is being used. The login service not only sends data but also includes a header. I am wondering how I can effectively read both the data and header on the AngularJS ...

Switching back and forth between fluid text fields

Is there a way to navigate between dynamically generated textfields using an iterator from struts-tags? <s:iterator value="aList"> <td width="50px" align="center"> <s:textfield name="solField" size="2" maxlength="1" style="text-transform ...

"Overlooked by z-index, absolutely positioned overlay causes confusion

I have been working on a template where I am trying to create a glow effect in the center of three divs with different color backgrounds. I added an absolutely positioned container with 10% opacity, but it ended up overlaying everything and ignoring z-inde ...

The issue with the functionality of position absolute in CSS when used with JavaScript

<html> <head> <style> #wrapper{ position: absolute; top : 250px; width: 500px; height: 500px; border: 1px solid red; } .tagging{ position: absolute; border: 1px solid black; width : 20px; height: 30px; } & ...

Utilizing a range input (slider) to extract data of importance

When dynamically adding a slider to a page using a specific string, like the one shown below: "<input type=\"range\" name=\"aName\" min=\"1\" max=\"9\"/>"; After appending it to the page with pure JavaScript, ...

Issues with div placement arise when incorporating relative positioning and floats

I have been attempting to position two divs with images next to the other divs but they appear underneath them instead. Can someone help me figure out what I am missing? FIDDLE CSS #main { margin: 0 auto; } #header { clear:both; float:left; ...

Retrieving a specific data point from the web address

What is the most efficient way to retrieve values from the window.location.href? For instance, consider this sample URL: http://localhost:3000/brand/1/brandCategory/3. The structure of the route remains consistent, with only the numbers varying based on u ...

Showing the values of two distinct select boxes in a URL

Here are both select boxes, the goal is to display selected values from both in the URL. This can be achieved by displaying them like this: e.g www.example.com#135+#140 OR www.example.com#135&140 (The order of values doesn't matter as long as bot ...

The width of table columns is altered upon the second rendering in JQuery DataTables

Is there a way to prevent JQuery DataTables cells from extending width after adding hyperlink to cell? I am facing an issue where I have two tables on the same page. The first table column has a link which populates the second table. It works fine when th ...

Is my Magento journey on the correct course?

I am wanting to include or require a file in DATA.php within magento. Below is the code snippet I have: public function formatPrice($price) { require_once(Mage::getBaseDir('app').'\design\frontend\neighborhood ...

Is your prop callback failing to return a value?

I am currently utilizing a Material UI Table component in my ReactJS project and I would like to update a state variable whenever a row is selected or deselected. The Table component has an onRowSelection prop that gets triggered each time a row is is sele ...

A clever JavaScript function generator encapsulated within an instant function nested within a jQuery ready statement

This code snippet features an immediate function enclosed within a jQuery ready function. $((function(_this) { return function() { document.write('called!'); }; })(this)); I am puzzled by where the resultant function ...