Manipulate object position using horizontal drag in Javascript

I am attempting to create a horizontal slider that can be dragged left or right, updating its transform translate position accordingly. My goal is to accomplish this using pure JavaScript without any external libraries.

Currently, my progress works upon initial load and allows for dragging to the desired position. However, it fails to update again after that.

var object = document.querySelector('.js-slider-container'),
initX, firstX;

object.addEventListener('mousedown', function(e) {

  e.preventDefault();
  initX = this.style.transform;
  firstX = e.pageX;

  this.addEventListener('mousemove', dragIt, false);

  console.log(initX);

  window.addEventListener('mouseup', function() {
    object.removeEventListener('mousemove', dragIt, false);
  }, false);

}, false);

object.addEventListener('touchstart', function(e) {

  e.preventDefault();
  initX = this.style.transform;

  var touch = e.touches;
  firstX = touch[0].pageX;

  this.addEventListener('touchmove', swipeIt, false);

  window.addEventListener('touchend', function(e) {
    e.preventDefault();
    object.removeEventListener('touchmove', swipeIt, false);
  }, false);

}, false);

function dragIt(e) {
  this.style.transform = `translate3d(${initX+e.pageX-firstX}px,0,0)`;
}

function swipeIt(e) {
  var contact = e.touches;

  this.style.transform = `translate3d(${initX+contact[0].pageX-firstX}px,0,0)`;
}

Check out this jsfiddle demonstration. It initially works, but then fails to update its position consistently. I'm also struggling with setting boundaries to prevent over-scrolling. Any insights would be greatly appreciated. Thank you!

Answer №1

Your this.style.transform initially holds an empty string "", but gets updated to translate3d(-578px, 0px, 0px) when dragged.

The issue lies in using the entire string value in calculations instead of extracting just the x value.

To rectify this, we can utilize a Regex to specifically extract the x value for accurate calculations as shown below:

 const txMatch = this.style.transform.match(/translate3d\((-?\d+)px,.+\)/);
 initX = txMatch ? +(txMatch[1] || 0) : 0;

// JavaScript code snippet for slider functionality

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

Use Vue's DOM manipulation to properly surround iframes with divs

I'm facing a scenario where my Vue component displays HTML content retrieved from the database in the following format: <div id="post-body-text" class="post__main-text" v-html="postText" ...

How can an array be transferred from app.get() to app.post()?

I am receiving an array from an ajax file that contains a list of products which I need to add to the order. My goal is to link the table of orderProducts and the order table together using a column called orderId. However, I am having trouble getting the ...

Automated updating feature with jQuery

Is there a way to use jQuery code to automatically refresh a page after navigating back in the browser history? Here is an example of what I have tried: jQuery(".form_" + form_count).html("<div id='message'></div>") jQuery('#me ...

What is the best approach to execute this function repeatedly at specific intervals?

I'm attempting to execute everything inside the checkUser() function, but it's not running at the specified interval. Is there a more efficient way to achieve this? My goal is to verify the address every few minutes. The line const accounts = awa ...

Detecting a targeted POST event in JavaScript without any libraries

In a situation I'm facing, an AngularJS website is not loading jQuery (except for jQLite). My goal is to monitor events with particular parameters. Unfortunately, I'm unable to make any changes to the source code. However, by examining the event ...

Tips for storing a string or object in a Firebase database

I'm looking for some guidance on how to save a string or object to the Firebase database using JavaScript. I'm currently trying to do this on codepen.io. Here's what I've attempted so far: // Setting up Firebase app const firebaseConfi ...

What is the best method for changing the value of a DOM element depending on the status of another element?

Imagine implementing a text field that triggers the following code on each keydown event: if( $('#my_input').val() == '' ) $('#my_span').html('my input is blank'); else $('#my_span').html('My inpu ...

Arrange array items according to the values of two attributes

Within my array of N objects, each object is structured with the following properties: { id: 'an id', description: 'a description', isUser: true/false } My goal is to sort this array based on two criteria: Firstly, any object w ...

Methods for transferring data from an AJAX function

I have a database containing various links that I would like to retrieve and store within an array. I attempted to achieve this using the following code: var amz = new Array(); function CreateAmazonArray() { $.ajax({ url: "php/amazon_affilia ...

What is the best way to stop Quasar dropdown list from moving along with the page scroll?

I am facing an issue with my code while using Quasar (Vue 3.0). The code snippet in question is: <q-select filled v-model="model" :options="options" label="Filled" /> When the drop-down menu is open and I scroll the pag ...

There was an error encountered while attempting to read the property 'webpackHotUpdate' of an undefined object

Encountering an error when the browser reaches the following line in the "webpackified" app.js file: /******/ (function(modules) { // webpackBootstrap /******/ function hotDisposeChunk(chunkId) { /******/ delete installedChunks[chunkId]; /****** ...

What is the best way to separate a string value with commas and send it to a controller?

Within my SQL table named Products, there is a field called AvailableSizes with a data type of NVARCHAR, which stores all the available sizes for a product. In my view, I have separated the values of the AvailableSizes field as shown below: <p> ...

ThreeJS Loading Page

Just starting out with ThreeJS and currently in the process of building a 3D Configurator. I'm looking to add a loading screen before the obj object loads, here's my current code: <!DOCTYPE html> </style> </head> <body& ...

Creating personalized categories with Material-UI's Autocomplete feature in a React application

I've been attempting to customize the groupings in the MUI Autocomplete component, but I haven't had any luck so far. It seems like there is no built-in solution provided by the library (I hope I'm mistaken). https://i.sstatic.net/NcJWU.png ...

What is the best way to align geometry at the bottom of the screen in Three.js while still preserving its aspect

I recently started using Threejs and encountered an issue with positioning geometry. I'm trying to place the geometry at the bottom with half of it cut off, so only half should be visible. However, when I use position.setY(-300), the geometry moves do ...

Tips for utilizing Material UI's Tooltip feature alongside a TableRow

I'm currently facing an issue where I'm trying to include a MUI TableRow inside a Tooltip component in order to display a long uuid when hovering over the row. However, I noticed that all the columns of the row are being compressed into the first ...

Conceal this element within the ng-repeat loop

Is there a way to hide a div containing values within it when a button is clicked? <div ng-repeat="item in items"> <p>{{item.name}}</p> <div>{{item.comment}}</div> <div id="button">show comment</div> < ...

"Empty array conundrum in Node.js: A query on asynchronous data

I need assistance with making multiple API calls and adding the results to an array before returning it. The issue I am facing is that the result array is empty, likely due to the async nature of the function. Any help or suggestions would be greatly appre ...

Websocket: Numerous users concurrently dragging a single item

I am currently implementing jquery drag and drop functionality with websockets. The goal is for any item dragged and dropped by a user to automatically update on other users' screens, similar to the demonstration in this video: https://youtu.be/JHndS1 ...

Refresh the information displayed in the HTML table

I've been assigned the task of developing a shift management web app to help our current employees track their shifts. The website StaffHub has been suggested as a reference for my web app, and I am currently focused on implementing the calendar featu ...