Optimal method for relocating an element efficiently

I'm currently working on a project where I need to implement horizontal movement for a DOM element. The movement should start on mousedown, continue on mousemove, and end on mouseup.

This task is especially challenging due to the site's numerous animations and elements, making performance a top priority. However, I have noticed a slight delay in the element's movement, causing it to lag behind the mouse. This issue is not ideal and affects the overall appearance of the site.

Here's a snippet of the current code I have:

var offset = 0, startX;
$('.draggable').on('mousedown', function (e) {
        startX = e.pageX;
    })
    .on('mouseup', function() {
        startX = null;
    })
    .on('mousemove', function (e) {
        if(startX) {
           newX = e.pageX;
           offset += newX - startX;
           startX = newX;
           this.style['-webkit-transform'] = 'translate(' + offset + 'px)';
        }
    });

(jsfiddle link)

I'm seeking advice on how to optimize this code for better performance. Are there any changes or techniques, such as using requestAnimationFrame and adjusting FPS, that could help improve the performance?

UPDATE: How can I enhance the performance of this code, especially in terms of requestAnimationFrame and FPS?

Answer №1

There is a slight improvement in the code below:

let startingPosition = 0, initialXCoordinate;
$('.draggable').on('mousedown', function (e) {
        initialXCoordinate = e.pageX - startingPosition;
    })
    .on('mouseup', function() {
        initialXCoordinate = null;
    })
    .on('mousemove', function (e) {
        if(initialXCoordinate) {
           startingPosition = e.pageX - initialXCoordinate;
           this.style['-webkit-transform'] = 'translate(' + startingPosition + 'px)';
        }
    });

Check out the fiddle

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

What is the process for deleting headers in a $http.get call and simultaneously including "application/json" and "text/plain" under the "Accept" header?

I'm relatively new to angularjs and I'm currently working on implementing some new features to an existing Angular JS application. The current API calls are quite intricate so I decided to make a direct call. Below is the code snippet for my new ...

Tips for linking two project routes in NodeJS and incorporating React (I am interested in invoking React within the NodeJS project)

I'm in the process of linking two projects, one using reactJS and the other NodeJS. Currently, NodeJS is running smoothly on localhost:3000. Next, I want to call a React application which redirects to port localhost:3001. How can I seamlessly connect ...

Unlock the potential of HTML5 Datalist: A comprehensive guide on integrating it with

The latest version of HTML, HTML5, has introduced a new tag called datalist. This tag, when connected to <input list="datalistID">, allows for autocomplete functionality on web forms. Now the question arises - what is the most efficient approach to ...

Guide on modifying values using both input fields and buttons at the same time

I am facing an issue with my input field that is designed to accept numbers. I want the value to be changed both via keyboard input and buttons. The buttons are functioning correctly unless I try to use keyboard input as well. For instance, if I enter 10 ...

Vue.js global event issue

Recently, I encountered an issue with the following code: <component-one></component-one> <component-two></component-two> <component-three></component-three> Specifically, component-two contains component-three. My cu ...

Can animations be stacked in a queue while using velocity.js?

I'm currently tackling a project involving a push menu. When the content div slides over, the menu buttons come in with a slight animation as they appear on the screen. However, if the user rapidly opens and closes the menu multiple times, the items o ...

React SVG not displaying on page

I am facing an issue with displaying an SVG in my React application. Below is the code snippet: <svg className="svg-arrow"> <use xlinkHref="#svg-arrow" /> </svg> //styling .user-quickview .svg-arrow { fill: #fff; position: ...

Subdomain for an Ajax request

Can we use ajax requests to extract data from and fetch information from pages like ? It appears that JavaScript still does not permit subdomain requests. ...

Is it possible for my node.js to become unresponsive when comparing lists?

In my node.js app, I have two lists - one retrieved from a database and the other created by listing file names on a server. Both lists contain approximately 750,000 strings each, and now I need to search for each string in one list within the other. As a ...

The ellipsis text-overflow feature occasionally malfunctions during a single session when using IE 11

.show-ellipsis { white-space: nowrap; text-overflow: ellipsis; overflow: hidden; } <div class="container"> <div class="row show-ellipsis"> {{record.bodyName}} </div> </div> My web application supports versions o ...

How can a borderless text field be created using Material UI?

Today, I delved into using Material UI for my React project. My goal is to create a registration form similar to this one. Essentially, I want 5 input text fields without any borders and with a simple background color effect when active. However, I'm ...

Ways to achieve a gradient effect on top of an image

Hey, I'm trying to implement a gradient on images in my project. Here's what I have so far: import Image from 'next/image' import Box from 'mui/material/Box' import PlayIcon from './PlayIcon.tsx' <Box ...

Trouble displaying CSS content image in Internet Explorer

Usually, I use Chrome as my default browser. However, I recently decided to test whether my website functions properly on other browsers as well. In Chrome, the header displays my logo with great quality using content:url. But when I tried accessing my w ...

Utilizing 'Ng-If' causes a glitch in the program during the execution of a $( '#x' ).change event or when adding a new item with AngularFire $add

After implementing ng-if in my code, I observed two specific instances where it caused unexpected behavior. The first instance involves using ng-if="isOwnProfile" for an image-upload toolbar. However, the use of ng-if resulted in the event listener ceasin ...

Describing a function in Typescript that takes an array of functions as input, and outputs an array containing the return types of each function

Can the code snippet below be accurately typed? function determineElementTypes(...array: Array<(() => string) | (() => number) | (() => {prop: string}) | (() => number[])>) { /// .. do something /// .. and then return an array ...

Invoke two functions simultaneously on a single Onchange event

Can someone help me understand how to trigger two functions by changing the value of a specific dropdown list using the "OnChange" event in Ajax? Note: The system typically only displays the output of the showhistory() function. Here is my existing code: ...

The fitBounds() method in Google Maps API V3 is extremely helpful for adjusting

I am trying to display a map on my website using this code: function initialize() { var myOptions = { center: new google.maps.LatLng(45.4555729, 9.169236), zoom: 13, mapTypeId: google.maps.MapTypeId.ROADMAP, panControl: true, mapTyp ...

Retrieving fresh CSS data from earlier animated elements within a Greensock timeline

In my code, I am using a TimelineLite() to perform a series of sequential tweens with .to(). What I want to achieve is accessing the output value from one of the early tweens in order to use it for constructing later tweens. Is there any way to retrieve t ...

Obtaining JSON data through AJAX requests from different domains may result in receiving a JSON string format

I have encountered an issue with my cross-domain AJAX call. It seems that instead of receiving a JSON object as expected, I am getting a string from the API provider. Here is the code snippet for my AJAX request. $.ajax({ async: false, ...

Is it best to remove trailing/leading whitespace from user input before insertion into the database or during the input process?

There's something I've been pondering that pertains to MVC platforms, but could also be relevant to any web-based platform that deals with user input forms. When is the best time and method to eliminate leading/trailing whitespace from user inpu ...