The act of manually moving an object with a mouse

I've been holding onto this question for quite some time, hesitant to ask because of potential backlash. Nevertheless, here I am finally sharing my dilemma in hopes of finding a solution...

Imagine there's an element on the page that can be dragged with the ID "dragme"... Now, instead of manually dragging it to a specific location every time, is there a way to automate this task using a function? Let's call this function "dropElement". Essentially, I want to simulate dragging "dragme" to wherever my mouse cursor is positioned using a script in jQuery or JavaScript.

This is what I've attempted so far:

(function() {
    'use strict';

    var mouseX = 0;
    var mouseY = 0;
    var timer = 0;
    
    document.body.addEventListener("mousemove", function(e) {mouseX = e.clientX; mouseY = e.clientY;});
    
    function dropElement() {
        $("#dragme").trigger($.Event("mousedown", {button: 0}));
        $("body").trigger($.Event("mouseup", {button: 0, clientX: mouseX, clientY: mouseY}));
        timer = setTimeout(dropElement, 100);
    }
    
    dropElement(); // executes function and drops "dragme" to mouse position

Answer №1

I found the solution in the question to be a bit intricate, especially with the inclusion of a timing function.

Instead of delving into complexities, I decided to simplify things by utilizing vanilla JavaScript and focusing on the sequence of actions. When a user moves the mouse, we only need to pay attention if they have clicked within the specific element that we want to drag. This code snippet introduces a variable called isDown, which is toggled to true when the user clicks down on the element.

Subsequently, it listens for the mousemove event across the entire window, and if isDown is true, it allows the user to drag the element.

In addition, it tracks the mouseup event on the window to reset isDown.

The rationale behind handling certain events on the actual element and others on the window is due to the dynamic nature of movement – there might be instances where the mouse leaves the window before being released, for instance.

let isDown = false;
const dragMe = document.querySelector('.dragme');
dragMe.addEventListener('mousedown', function() {
  isDown = true;
});
window.addEventListener('mouseup', function() {
  isDown = false;
});
window.addEventListener('mousemove', function() {
  if (isDown) {
    dragMe.style.top = event.clientY + 'px';
    dragMe.style.left = event.clientX + 'px';
  }
});
.dragme {
  width: 5em;
  height: 5em;
  background-color: cyan;
  position: relative;
  top: 0;
  left: 0;
}
<div class="dragme">Drag me</div>

Answer №2

I trust that this example provides assistance to you

var drag = {
   elem: null,
   x: 0,
   y: 0,
   state: false
 };
 var delta = {
   x: 0,
   y: 0
 };
 function dropElement(e){
   var cur_offset = $("#autoDrag").offset();
   $("#autoDrag").animate({
       left: (e.pageX),
       top: (e.pageY )
     });
 }
 $(document).mousedown(function(e) {
 dropElement(e);
 })
 $("#dragMe").mousedown(function(e) {
     drag.elem = dragMe;
     drag.x = e.pageX;
     drag.y = e.pageY;
     drag.state = true;
 })
$(document).mousemove(function(e) {
   if ( drag.state) {
     delta.x = e.pageX - drag.x;
     delta.y = e.pageY - drag.y;

     var cur_offset = $(drag.elem).offset();
     $(drag.elem).offset({
       left: (cur_offset.left + delta.x),
       top: (cur_offset.top + delta.y)
     });

     drag.x = e.pageX;
     drag.y = e.pageY;
   }
 })
 $("#dragMe").mouseup(function() {
    drag.state = false;
 })
#dragMe {
  position: absolute;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 80px;
  height: 80px;
  padding:10px;
  background-color: #00a1ff;
  color: white;
  border-radius: 50px;
}
#autoDrag {
  position: absolute;
  right:0;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align:center;
  width: 80px;
  height: 80px;
  padding:10px;
  background-color: #ff00ff;
  color: white;
  border-radius: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<span id="dragMe">DragMe!</span>
<span id="autoDrag">Click somewhere I will be there!</span>

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

about float and width

Having a sidebar and a content area, I initially floated the sidebar to the left and the content area to the right. However, as the screen size changes, a noticeable gap appears between the two floats. This issue seems to stem from the size of the image in ...

Determine the total number of active links on an HTML webpage using F#

Currently, I am working on developing a basic F# function that will be able to count the total number of links present in a given HTML website URL. I understand that this can potentially be achieved by counting the occurrences of the "<a" substrings, b ...

Protractor reusable variables

Struggling to extract values from Protractor testing for reuse? No worries, I've got you covered! Imagine this scenario: you have an app that generates new records through a form and then showcases them to the user. Upon successful addition, a messag ...

Show an xeditable form that can be edited within a popup window

Looking for a way to enclose the editable form within a bootstrap uib-popover-template. Tried the editable ui-bootstrap popover method, but encountering unexpected issues. Check out Plunker 1 --> https://plnkr.co/edit/vXeVoFYVU2IU08CF Issue with angul ...

Tips for aligning a row at the bottom within a nested column

Desired Outcome I am struggling to arrange two smaller images next to a larger image using Bootstrap 4. Specifically, I am having difficulty aligning one of the smaller images at the bottom so that it matches the alignment of the larger image. The layout ...

Having trouble loading the .php file with my Ajax request

Attempting to retrieve data from the postcode.php file and display it in a #postcodeList div, but encountering issues as nothing happens. Upon inspecting the postcode.php file, it seems to be outputting all the correct information. var loadicecream = do ...

Ways to output a string array from a JSON object containing additional attributes

On the client side, I have received a JSON object from a REST service. This object contains multiple attributes, one of which is a String array. I need guidance on how to display this array using embedded AngularJS code in HTML. Here is my JSON object: [ ...

Is it possible to disregard JQMIGRATE warnings for AngularJS v1.4.5 and proceed with upgrading AngularJS?

I currently have jquery 2.2.4 and AngularJS v1.4.5 integrated into my website. After setting up jquery-migrate-1.4.1, I encountered the following warning: JQMIGRATE: jQuery.fn.attr('selected') might use property instead of attribute The issue s ...

The background image in the header does not fully extend to cover all of the header content

I am currently working on a website for a friend and I am facing an issue with the header section. The header is a div that contains two images inside divs, as well as the company name and slogan in separate divs. The main purpose of this header div is to ...

leveraging ajax callbacks, the significance of http status codes and essential validation concepts

Recently, I've been working on a server side AJAX class designed to return a JSON string in response to an AJAX request. One question that has been on my mind is when it would be appropriate to return HTTP status codes based on the server's respo ...

Ways to retrieve information from JSON

I am currently trying to access the values of an object that is within an array which is inside another object. The data is structured as follows: [{ "id": "99a4e6ef-68b0-4cdc-8f2f-d0337290a9be", "stock_name": "J ...

Utilize the HTTP path to designate the currently active tab

Here is a sample code snippet for vertical tabs in React using the Material-UI library: import * as React from 'react'; import Tabs from '@mui/material/Tabs'; import Tab from '@mui/material/Tab'; import Typography from '@ ...

Extract objects from a nested array using a specific identifier

In order to obtain data from a nested array of objects using a specific ID, I am facing challenges. My goal is to retrieve this data so that I can utilize it in Angular Gridster 2. Although I have attempted using array.filter, I have struggled to achieve t ...

Animating elements in Nativescript Vue using v-show and transitions

I am facing some issues while using v-show with Nativescript. I attempted to create an animation as outlined in . When using v-show, the element doesn't completely disappear from the screen. Below is my code: <template> <Page actionBarHi ...

Understanding how to properly handle the data sent by an ajax request in a NodeJS server

I currently have an array called passedWord = ['a', 'bbb']. I am then making an AJAX request to send this array to a Node.js server. Upon receiving the array on the server, Body Parser returns the following object: { name: 'abc&ap ...

Tips for adjusting the width of items within the Box element in Material UI React

I am utilizing React Material UI along with the Box component to style my form. In this scenario, I have 4 items in each row except for the last row where I need to display only 3 items with the last item filling the entire row by merging two elements toge ...

Diagnosing Issues with Yii2's $(document).ready Function

AppAsset: public $js = [ 'plugins/jquery/jquery.min.js', 'plugins/jquery/jquery-migrate.min.js', 'app.js', ]; When I write this in a view file: $script = <<< JS jQuery(document).ready(function( ...

What is the best way to align a div right below an image that has been clicked on?

I am designing a website that features social media icons spread out horizontally across the page. When a user clicks on one of these icons, I envision a pop-up window appearing below it, displaying additional information. Here is a visual representation o ...

Activate $digest when a variable is modified by a node.js function

I am currently working on developing an application using node-webkit and AngularJS. Everything was going smoothly until I tried to make Angular watch over a "legacy variable" using the method outlined in this answer, which led to an Error: [$rootScope:inp ...

Guide on invoking a method from a class in a different file

Seeking a solution to a task involves calling a function from a different file within a class. Here's what I am trying to achieve: file1 export class Example { constructor() { ... } myCustomFunction = () => { ... } } file2 impor ...