The functionality for dragging elements is not functioning properly in JavaScript

Here is the code I used in an attempt to make a div element draggable:

let div = document.querySelector('div')
div.onmousedown = function() {
  div.addEventListener('mousemove', move, true)
}
window.onmouseup = function() {
  window.removeEventListener('mousemove', move, true)
}

function move(e) {
  this.style.position = 'absolute'
  this.style.top = e.clientY + 'px'
  this.style.left = e.clientX + 'px'
}
div {
  background: red;
  width: 100px;
  height: 100px;
}
<div></div>

Unfortunately, the code does not work as expected and there seems to be an issue with the positioning when hovering over the div. It appears that there may be unintended side effects that are affecting the positioning. Upon reviewing the code, it doesn't seem like any mouseover-related actions were defined.

If anyone can provide insight into what might be causing this unexpected behavior and how to resolve it, I would greatly appreciate it!

Thank you for any assistance!

Answer №1

Make sure to remove the event listener from the specific div element, not from the window:

I have also implemented centering of the div while the user is dragging it, preventing the mouse from escaping the div.

let draggableDiv = document.querySelector('div');

function moveElement(e) {
  this.style.position = 'absolute';
  this.style.top = e.clientY - (this.offsetHeight / 2) + 'px';
  this.style.left = e.clientX - (this.offsetWidth / 2) + 'px';
}

draggableDiv.addEventListener('mousedown', function() {
  this.addEventListener('mousemove', moveElement, true);
});

window.addEventListener('mouseup', function() {
  draggableDiv.removeEventListener('mousemove', moveElement, true);
});
div {
  background: red;
  width: 100px;
  height: 100px;
}
<div></div>

Answer №2

There were a couple of issues that needed addressing:

  1. The event listener was being removed from the window instead of the div element.
  2. It is important to take into account the offset values in order to accurately position the div when moving it.

let div = document.querySelector('div')
let offsetX = "";
let offsetY = "";

div.onmousedown = function(e) {
  var domRect = this.getBoundingClientRect();
  offsetX = e.clientX - domRect.left;
  offsetY = e.clientY - domRect.top;
  div.addEventListener('mousemove', move, true)
}

window.onmouseup = function() {
  div.removeEventListener('mousemove', move, true)
}

function move(e) {
  this.style.position = 'absolute'
  this.style.top = e.clientY - offsetY + 'px'
  this.style.left = e.clientX - offsetX + 'px'
}
#my-div {
  background: red;
  width: 100px;
  height: 100px;
}
<div id="my-div"></div>

Answer №3

makeDraggable(document.getElementById("myelement"));

function makeDraggable(el) {
  var x1 = 0, x2 = 0, y1 = 0, y2 = 0;
  
  if (document.getElementById(el.id + "header")) {
    document.getElementById(el.id + "header").onmousedown = startDragging;
  } else {
    el.onmousedown = startDragging;
  }

  function startDragging(e) {
    e = e || window.event;
    e.preventDefault();
    
    x1 = e.clientX;
    y1 = e.clientY;
    
    document.onmouseup = stopDragging;
    document.onmousemove = moveElement;
  }

  function moveElement(e) {
    e = e || window.event;
    e.preventDefault();
    
    x2 = x1 - e.clientX;
    y2 = y1 - e.clientY;
    
    x1 = e.clientX;
    y1 = e.clientY;
    
    el.style.top = (el.offsetTop - y2) + "px";
    el.style.left = (el.offsetLeft - x2) + "px";
  }

  function stopDragging() {
    document.onmouseup = null;
    document.onmousemove = null;
  }
}
#myelement {
  position: absolute;
  z-index: 9;
  background-color: #f1f1f1;
  text-align: center;
  border: 1px solid #d3d3d3;
}

#myelementheader {
  height: 100px;
  width: 100px;
  cursor: move;
  z-index: 10;
  background-color: #2196F3;
  color: #fff;
}
<h1>Resizable Element</h1>

<div id="myelement">
  <div id="myelementheader"></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

Modify JSON date format to a shorter version using the first 2 letters of the month and the year

Looking to convert date values in a JSON array from "December 2016" format to "D16". Hoping to accomplish this using Regex, any assistance would be greatly appreciated. [["November 2016","December 2016","January 2017","February 2017","March 2017"],["tot ...

Can you combine multiple user validation rules with express-validator?

I have a set of rules that are almost similar, except for one where the parameter is optional and the other where it is mandatory. I need to consolidate them so that I can interchangeably use a single code for both cases. Is there a way to merge these rul ...

What methods do publications use to manage HTML5 banner advertisements?

We are working on creating animated ads with 4 distinct frames for online magazines. The magazines have strict size limits - one is 40k and the other is 50k. However, when I made an animated GIF in Photoshop under the size limit, the image quality suffered ...

Design a layout consisting of a grid with items that maintain a set maximum width while being evenly distributed across the entire width of the device

I'm trying to create a grid with 2 rows and 3 columns, each cell having an image with a max-width of 512px. I added margin to the grid but now the cells are larger than the content. How can I achieve the same visual appearance as flexbox's justif ...

Transform JSON time data from Coordinated Universal Time (UTC) to Indian Standard

Hello, I consider myself an amateur in the world of online javascript learning. Currently, I have come across a challenge that has left me stuck. I am working with a JSON time data provided in UTC format (e.g. 16:00:00Z) and my goal is to convert it to IS ...

Execute tests on changing files using cypress.io

I'm currently experimenting with using Cypress to test a large Angular application that I've developed. What I want to achieve is to load an expectation file into my test and then run the test based on this expectation file. Despite trying diffe ...

Eliminate repeated elements in a selection using an AngularJS custom directive

I am in the process of creating an events app that utilizes JSON data from Drupal to showcase events using AngularJS within a Drupal module. One of the keys in the JSON object is 'genre', which I'm utilizing in a select dropdown to allow use ...

The CSS files undergo modifications when executing the command "npm run dev"

I've been working on an open-source project where I encountered a bug. Even when there are no images to display, the "Load More" button in the web browser extension still appears. To fix this, I decided to add the class `removeButton` to the button an ...

How to perfectly align squares in CSS Grid

I'm working on arranging four squares in a grid pattern, two on top and two on the bottom, with equal spacing between them. Currently, the squares shift based on the fr value in CSS grid, resulting in uneven spacing like this: I want to align all fou ...

Unable to retrieve post information from Angular using PHP

I've hit a roadblock in my Angular App where I can't seem to access the body of the post data being sent from Angular 4. Despite numerous attempts, I'm unable to retrieve this crucial information. Can anyone lend a hand in identifying the is ...

Ways to change the chart type in ApexCharts

I'm seeking a way to change the chart type of an existing ApexCharts that has already been rendered. After reviewing the methods, I attempted to use the updateOptions() method, but encountered the error: Uncaught TypeError: Cannot read property &apos ...

Creating a stunning horizontal bar chart with the react-d3-components framework

I am currently implementing a D3 chart using the react-d3-components library. So far, I have successfully generated a vertical bar chart. However, my specific requirement is to create a horizontal bar chart. import React from 'react'; import Reac ...

Why does this asynchronous function initially return nothing, only to suddenly return all results on subsequent tries?

My current task involves inserting data into my database within a map loop. To ensure that the loop completes before proceeding, I am utilizing an async function to store all results in the variable "practicasAgregadas." This is how I invoke the function: ...

What is the proper way to mention JavaScript packages when including them as parameters in Angular elements within HTML?

I was looking to enhance the command to be more authoritative. <div (click)="lastCall(999)">click me</div> My attempt to utilize Number.MAX_SAFE_INTEGER resulted in an error from my computer stating that it wasn't recognized. As a result ...

"Learn how to update an existing table row and populate its cells with JSON data retrieved from a successful AJAX request without creating a

Currently, I am utilizing CouchCMS. The platform offers a feature known as repeatable regions which essentially generates tables to showcase recurring content. The defined repeatable region looks like this: <cms:repeatable name="item_detail" ...

Unforeseen SyntaxError: Unexpected symbol detected

Encountering an issue while attempting to send raw data as parameters in express. Specifically, there is an error occurring at the 'fields' variable... function getWithQuery(req,res){ console.log(req.params); var query = {name: new RegEx ...

Having trouble accessing req.user on my Node.js server using Auth0 and Angular

Currently, I am utilizing auth0 for my admin panel's login system and it is functioning smoothly. However, I have encountered an issue in node where 'req.user' is returning as undefined for some unknown reason. This setup is fairly basic; I ...

Saving data values for utilization in jQuery

Recently, I've come across a series of links structured like this: <a class="colorBox" href="#" title="#0676B3"></a> <a ... <a ... these links all have color values in the title attribute <a ... What I'm trying to do is uti ...

Issue with React Google Maps Api: Error occurs while trying to access undefined properties for reading 'emit'

I'm trying to integrate a map using the google-map-react API, but I keep encountering the following error: google_map.js:428 Uncaught TypeError: Cannot read properties of undefined (reading 'emit') at o.r.componentDidUpdate (google_map.js: ...

The object's type remains a mystery

While working on implementing jwt authentication in Ionic, React with TypeScript, I faced a typescript error when trying to add a check in my App.tsx file after successful implementation. The error stated: Object is of type 'unknown' Below is ...