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

Share a URL and display small previews from it - php

Have you ever noticed that on certain websites, such as Facebook, when you post a link it automatically displays thumbnails from the linked website? Like in the image below: Ever wondered how to achieve that effect? ...

Issues arise with the HTML application cache while in offline mode after clicking the refresh button

I have encountered a problem with my web app that has been developed using application cache. I am currently testing it on Windows Phone 8.1 with the IE 11 mobile browser. Everything works smoothly when the internet connection is turned off and the web a ...

What is the best way to re-render a component immediately following an update in React?

As I attempt to change the color of a bar to green and then back to black, it seems like the latter color update is taking precedence in my code. const [color, setColor] = useState("black") const bubbleSort = async () => { const sleep = ms => ...

Make the width of a table column match the width of the header

I am currently using Primeng2 datatable and I am looking to adjust the column width to match the header size. This is my HTML code: <p-dataTable #dtselfcollectmonthly [exportFilename]="exportname" [rows]="10" [value]="rawdatatrucks"> <ng-con ...

Problems encountered when trying to deploy on Firebase

I've been working on deploying my web app to Firebase, and I successfully ran the deploy script. However, when I try to access the URL, instead of seeing my app, I'm greeted with the Open Hosting Documentation page. Here is what my firebase.json ...

The execution of the return statement in the catch block is unsuccessful

Here is a simple example that results in an error because the variable tl was not specified: function allmatches() { SpreadsheetApp.getActive().getSheetByName('data').getRange('A1').setValue(tl) } To track any errors that occur durin ...

Changing a variable with Functions and Objects

I'm curious to know what the index variable returns in this code snippet. I believe it will be 0. function jsTest() { var index = 0; var counter = 0; var obj = {}; obj.index = index; var func = function () { for (index ...

Understanding the differences between jquery's addClass method and the .css()

After creating a function to set a background on a click event, I encountered an issue. I attempted two different methods, expecting both to be successful. However, only the .css() version worked while the addClass method failed. Why is this happening? fu ...

Setting Up AdminLTE Using Bower

Recently, I decided to incorporate the Admin LTE Template into my Laravel project. I diligently followed the guidelines outlined here As soon as I entered the command: bower install admin-lte The installation process seemed to start, but then the ...

Verify if the specified value is present in the dropdown using AngularJS

Utilizing AngularJS, I have implemented an input field with autocomplete functionality. The autocomplete feature pulls data from a JSON file and displays it in a dropdown table format. Users are able to filter the results and select a value from the dropdo ...

What is the best way to transfer Kendo Grid row data to a Kendo popup window within a partial view using jQuery?

I am currently facing a challenge in passing the row data from the Kendo Grid to a partial view that is displayed through a Kendo popup window. Within the partial view, users have the option to upload an image file related to the specific row record. This ...

Where should AJAX-related content be placed within a hyperlink?

When needing a link to contain information for an AJAX call, where is the correct place to include the info? I have typically placed it in the rel attribute, but after reviewing the documentation for rel, it appears that this may not be the right location ...

What is the best way to place a transparent navbar on top of a hero image while also adding a functional button to the hero image?

My navigation bar is set to be transparent on top of my hero image, but the buttons on the hero image are not clickable. The nav-bar has a z-index of 1, while my hero image, text, and button have a z-index of -1. This setup causes the button to be unclick ...

Using an external variable within an internal function in TypeScript

I am facing a situation where I have a variable outside of a function that needs to be updated, but I am unable to access it using "this" as it is not reachable at that point in the code. export class GamesDetailPage { details : any = {}; type : St ...

"Exploring the process of retrieving data from a request in Node.js with the help of the Express

I'm encountering some issues with integrating a "login" form into my Node.js script. While I can get it to work using a static HTML page, utilizing a dynamic ".ejs" page is causing trouble as my form fields are showing up as "undefined". var helmet = ...

Footer overlapping occurs on a single page

My webpage is having an issue where the footer is overlapping. It seems to be fine on all other pages except for this one. I would prefer not to make any changes to the footer since it's working correctly on other pages. Is there a way to adjust the C ...

Stop the occurrence of OpenCPU javascript error pop-up notifications

I'm currently experiencing an error related to CORs during a test deployment of OpenCPU. While I may create a separate question for this issue in the future, for now, I am wondering if it is possible for the deployment to fail without alerting the end ...

Retrieve data from jQuery and send it to PHP multiple times

<input type="checkbox" value="<?= $servicii_content[$j]['title'] ?>" name="check_list" id="check" /> By using jQuery, I am able to extract multiple values from the table above once the checkboxes are checked. Here's how: var te ...

Unique border-bottom width measurements available

Seeking assistance with a design challenge, further details are available in the screenshot I've provided. I am attempting to apply a unique border bottom style to or text, with specific width specifications that do not span the entire word length. ...

Attempting to send a variable from JavaScript to PHP while inside an "if" statement

I've been attempting to pass a variable within an if statement, but for some reason the PHP file isn't receiving the variable. Below is the code I'm working with: JS: if(data.details.payment_type =="sofo") { var orderid = data.deta ...