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

Struggling to concentrate on the branding

I've been using materializecss for some time now and recently encountered an issue while trying to navigate my website using keyboard tabbing. The checkbox in materializecss is a custom CSS checkbox, but when I set the tabindex for the label of the c ...

A guide on converting array values to objects in AngularJS HTML

Here is my collection of objects: MyCart = { cartID: "cart101", listProducts : [ {pid:101, pname:"apple", price: 200, qty:3}, {pid:102, pname:"banana", price: 100, qty:12} ] } I have incorporated a form in ...

I am facing difficulty in incorporating an IP address or URL within an IFRAME in my Cordova Android application

This page does not allow any iframes to load except for the YouTube video URL. When attempting to use any other iframe URL, the following error code is displayed: Error : net::ERR_BLOCKED_BY_RESPONSE In the example below, any URL or IP address fails to l ...

Why is the `node-config` configuration undefined within a TypeScript Jest environment?

I have a TypeScript module that is functional in both development and production environments. It utilizes https://github.com/lorenwest/node-config. When I attempt to import it into Jest for testing purposes, I encounter an error suggesting that the config ...

Tips for utilizing ng-repeat with a function that generates a fresh object?

My HTML code includes the following element: <button ng-click="console.log(key)" ng-repeat="(key, value) in getLocalStorageKeys() track by $index"> In my JavaScript file, I have the following function: $scope.getLocalStorageKeys = function(){ ...

Looping through JSON keys using ng-repeat in AngularJS

I am currently working on a project where I need to populate some JSON data retrieved from the Google Tag Manager API and then send this information to the frontend which is developed in AngularJS. At the moment, I am utilizing ng-repeat on a card compone ...

Consistentize Column Titles in Uploaded Excel Spreadsheet

I have a friend who takes customer orders, and these customers are required to submit an excel sheet with specific fields such as item, description, brand, quantity, etc. However, the challenge arises when these sheets do not consistently use the same colu ...

Troubleshooting Issues with Loading Styles and JavaScript for Wordpress Plugin in Admin Area

Can someone please help me with troubleshooting my stylesheet and scripts that are not working properly? I have included styles in the stylesheet and an alert in my script file, but for some reason they are not functioning as expected. (I have confirmed ...

Meteor is only returning a portion of the values from the child array

I have a list structured as follows: { _id: xKdshsdhs7h8 files: [ { file_name : "1.txt", file_path : "/home/user1/" }, { file_name : "2.txt", file_path : "/home/user2/" } ] } Currently, I ...

Wrap text elegantly around your images with Flex Mobile

Looking to develop a component for a Flex Mobile app that will allow me to have text wrapped around an image, similar to what you see in articles or blogs. In HTML, this can be achieved with a tag like: <image align='right' /> associated t ...

The footer should always be anchored at the bottom of the webpage, maintaining a consistent position regardless of any changes to the browser's

I've successfully implemented a footer with several buttons that remains positioned at the bottom of the page, 60px above the very bottom, regardless of the content or window size. The CSS I'm using is as follows: #container { min-height: 10 ...

Securing page access with a straightforward password protection using Flask

Looking for a straightforward way to add password protection to a Flask app site. I've explored options like flask_login, but they seem overly complex for my needs. I don't need high security or login sessions - just something like: "enter passw ...

Creating a User-friendly Layout for Admin Pages in Next.js Version 13

Hey there, I'm facing an issue with the layout while using Next.js 13 Experimental App Directory. On my website's index page or routes '/', I want to show a landing page and use a specific layout for all pages except for those under the ...

The image loading and completion count function in JavaScript experiences sluggish performance on mobile devices

While this feature performs optimally on all the desktop browsers I've checked, it tends to have a glitch on mobile browsers. It often skips from 0% to 100% right away upon loading, or shows only a few numbers in between like 0%, 30%, 67%, 100%. Is th ...

Steps to create a fixed pattern background image with a customizable background color based on the content within a div element

I am seeking guidance on how to create a single page application using Angular that features a fixed background image (such as a white pattern) in the BODY tag. However, I would like the ability to change the color behind this image depending on the conten ...

Enhance data granularity in Jquery Flot by zooming in as the user interacts

I'm currently working on creating an interactive chart that allows users to zoom in for a more detailed view of the data. For instance, when viewing data over a default zoom period of 3 months, there would be one data point displayed every 24 hours. H ...

Eliminate any additional spacing or padding surrounding the text input field

Is there a way to adjust the inner padding of a text field? Currently, when entering text in an HTML text field, there is padding at the beginning and end. The numbers I am inputting have no more than 3 digits, and the current padding takes up about the wi ...

Different types of video formats used for html5 video players

Looking for some guidance here. I'm currently in the process of developing a website that allows users to upload their own videos. For the video player, I've opted for the HTML5 player by . My main concern is ensuring that the HTML5 player can on ...

Using HTML and CSS to create nested divs floating to the left while also incorporating a

I'm trying to create a simple effect where a fixed height and width div contains a series of child divs that can be scrolled horizontally. However, the children are not floating as expected in the following code: .a {width:200px; height:200px; ...

Order the results by a predicate chosen by the user and a predefined secondary attribute

Trying to organize a table of results by a user selected criterion and then by a predefined secondary one. For instance, the ng-repeat setup looks like this: <tr ng-repeat="line in model.resultList | orderBy:['-predicate', 'secondary_va ...