What is the best method for developing a draggable element that remains stable?

I have developed a simple script for draggable elements, however, I am facing an issue. Whenever I move the mouse quickly, the element loses focus.

Is there a way to improve the stability of the dragging functionality regardless of how fast I move the mouse?

You can view the demo I created here: https://www.w3schools.com/code/tryit.asp?filename=GGPV1ESRELL8

<html>
<head>
<style>

.tester {
    position: absolute;
    width: 150px;
    height: 150px;
    box-shadow: 0 0 10px black;
    background-color: white;
    cursor: pointer;
}

</style>
</head>
<body>

<div class='tester'></div>

<script>

let tester = document.querySelector('.tester');
let draggable = false;
let offX;
let offY;

tester.onmousedown = (e) => {
    e = e || window.event;
    offX = e.offsetX;
    offY = e.offsetY;
    draggable = true;
    tester.style.backgroundColor = 'indigo';
}

tester.onmouseup = () => {
    draggable = false;
    tester.style.backgroundColor = 'white';
}

document.body.onmousemove = (e) => {
    e = e || window.event;
    if (draggable){
        tester.style.left = (e.pageX - offX) + 'px';
        tester.style.top = (e.pageY - offY) + 'px';
    }
}

</script>
</body>
</html>

Answer №1

var chosen = null, // Object of the selected element to be moved
    x_pos = 0, y_pos = 0, // Tracking x & y coordinates of the mouse pointer
    x_elem = 0, y_elem = 0; // Keeping top, left values (edge) of the element

// Executed when user starts dragging an element
function _drag_initialize(elem) {
    // Save the object of the element which will be moved
    chosen = elem;
    x_elem = x_pos - chosen.offsetLeft;
    y_elem = y_pos - chosen.offsetTop;
}

// Executed while user is dragging an element
function _move_element(e) {
    x_pos = document.all ? window.event.clientX : e.pageX;
    y_pos = document.all ? window.event.clientY : e.pageY;
    if (chosen !== null) {
        chosen.style.left = (x_pos - x_elem) + 'px';
        chosen.style.top = (y_pos - y_elem) + 'px';
    }
}

// Reset the object once done
function _clear() {
    chosen = null;
}

// Attach the functions...
document.getElementById('draggable-element').onmousedown = function () {
    _drag_initialize(this);
    return false;
};

document.onmousemove = _move_element;
document.onmouseup = _clear;
body {padding:10px}

#draggable-element {
  width:100px;
  height:100px;
  background-color:#666;
  color:white;
  padding:10px 12px;
  cursor:move;
  position:relative; /* necessary (all positions other than `static`) */
}
<div id="draggable-element">Drag me!</div>

This code was sourced from https://jsfiddle.net/tovic/Xcb8d/

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

Guide to highlighting manually selected months in the monthpicker by utilizing the DoCheck function in Angular

I'm facing an issue and I could really use some assistance. The problem seems quite straightforward, but I've hit a roadblock. I have even created a stackblitz to showcase the problem, but let me explain it first. So, I've developed my own t ...

The ReactJS redirect URL is constantly changing, yet the component fails to load

I recently started using reactjs and I encountered an issue with routing from an external js file. Here is the code in my navigation file, top-header.js import React from 'react'; import {BrowserRouter as Router, Link} from 'react-router-do ...

A guide to determining the dimensions (width, height, length) of a mesh using THREE.js

I've been scouring different sources in hopes of finding a way to obtain the width and height of a mesh, but I haven't had any luck. I have imported a collada model into my project, and all I need is to determine its dimensions in Webgl/Three.js ...

Utilizing MongoDB Data in an .ejs Template Using Node.js Express

After going through numerous tutorials, I find myself stuck at a point where I am struggling to render all the data written by my express-app into MongoDB in embedded JavaScript. My goal is to display this data in a simple table that always shows the updat ...

Error message 'Object doesn't have support for this property or method' is triggered by a basic JSON object

Recently, I developed a compact framework for loading resources asynchronously (hyperlink). The framework functions properly in modern browsers such as Opera, Chrome, and Firefox. However, when testing it in IE8, the code fails to execute. Internet Explor ...

Updating the text of an element will occur only when the specified condition has been met

I am trying to dynamically change the text within the <span data-testid="recapItemPrice">ZADARMO</span> element from 'ZADARMO' to 'DOHODOU' only when the text inside the parent element 'INDIVIDUÁLNA CENA PREP ...

Experiencing a blank array when using filtering/search text in a Nodejs application with MongoDB

I am experimenting with search functionality in a MongoDB database using Node.js. However, my result array is always empty. I have shared my code here and would appreciate some assistance in identifying the issue. Whenever I perform a search, I end up with ...

What are some ways to restrict dynamic form submissions?

$(document).ready(function(){ var i = 1; $('#add').click(function(){ if(i < 5){ i++; $('#dynamic_field').append('<tr id="row'+i+'"><td><div class="form-group">& ...

The decision will be dependent on the outcomes provided by the $resource promise

I have been working on calling my API with AngularJS to retrieve a list of 'reports' and then displaying them in a modal or saving the sale depending on whether any results were returned. I've been struggling with this for a while and would ...

What is the best way to place tfoot at the top of the table

Below is the structure of my table: https://i.stack.imgur.com/QmlVn.png In the table, there are search input fields at the bottom of each column. I would like to move them to the top, right after the <thead> </thead>. The basic HTML code for ...

Libraries that automatically suggest options for integrating objects described by JSON schema

We are currently developing a platform with an email templating feature. Users can insert objects and variables into their emails using json-schema. Although we are not the first ones to work on this, our research has not turned up many libraries that cou ...

Why isn't the pipe working when trying to extract the last 2 characters using

I am currently working on creating a regex pattern to extract the variables passed to a JavaScript constructor. The format of the input data will always be similar to this: app.use(express.static('public')); The regex I have devised to remove ...

Trouble Arising from Regional Settings in my Hybrid App Developed with CapacitorJS and Vue.js

Issue with capacitor app input Correct input in chrome app I'm facing a problem related to regional settings in my mobile application, developed using CapacitorJS and Vue.js 2. The datetime-local control is appearing in a language that isn't the ...

Add HTML and JavaScript code dynamically with JavaScript

Currently, I am working on a project that involves an HTML table with some basic JS interactions triggered by user clicks. The structure looks something like this: htmlfile.html ... ... position action ...

Struggling to add an object to my Topic array using push

I'm in the process of developing a forum platform. Below is my Topic schema: const topicSchema = new mongoose.Schema({ author: { type: String, ref: "User", // Reference to the user who created the Topic required: true, }, t ...

Guide on Redirecting to a Welcome Page with a Passed Username Prop using Inertia.js in Laravel 9

I am currently developing an Application using Laravel and vue.js with Inertia. In this application, I have implemented a login page where users can enter their credentials. Upon successful authentication, the user should be redirected to the "Welcome.vue" ...

Having trouble aligning two divs on the same line and adjusting the controls to expand their width when there is extra space

I am currently creating an application using React and Material UI, incorporating the autocomplete control feature. Take a look at the code sandbox I have set up. Here are some concerns: I am aiming to have two autocomplete controls displayed on the same ...

Enhanced jQuery Embed Code validation for user input using a textarea

Currently, I am developing a website that allows users to input embed codes from popular platforms such as Twitter, YouTube, Instagram, Facebook, and so on. The embed code undergoes validation checks and is saved if it meets the criteria. However, when us ...

Retrieve the latency of the interaction.reply() method

While there have been many inquiries regarding how to create a ping command for a discord.js bot, my question stands out because I am attempting to develop this command for interaction rather than message. I attempted utilizing Date.now() - interaction.cre ...

The Angular Universal error arises due to a ReferenceError which indicates that the MouseEvent is not

I am encountering an error while trying to utilize Angular Universal for server-side rendering with the command npm run build:ssr && npm run serve:ssr. This is being done in Angular8. /home/xyz/projects/my-app/dist/server/main.js:139925 Object(tslib__WEB ...