Is there a way to implement a button that generates a draggable DIV when clicked, and assigns the dragging functionality to the newly created DIV?

I have yet to start writing any code for this, but I will try to draft some pseudocode to explain my idea clearly. The concept is that when a user clicks and holds on a 'button' (which may not actually be a button), a movable DIV is spawned. Once the DIV is created at the mouse position (slightly offset so the mouse is inside the div), I want to change focus to the new DIV so it can be positioned on the screen. This involves some operations on the DIV, but those details are not relevant to my question.

In incomplete pseudocode, here is what I am aiming for; my main query here is how to switch focus:

<script>
function NewDiv()
{
   var newDiv = CreateDiv(MouseX, MouseY);
   GrabDiv(newDiv);
}

function CreateDiv(X, Y)
{
    // Creating a new DIV in the DOM...handled.
    // Making it movable with JQuery...done.
    newDiv.style.left=(X - 3) + "px";
    newDiv.style.top=(Y - 3) + "px";

    return newDiv;
}

function GrabDiv(div)
{
    // Here's where I need help...

}

</script>

<input type='button' onMouseDown='NewDiv();' value="Spawn a new Div" />

The crux of my question lies in the 'GrabDiv' function. Any advice or feedback would be greatly appreciated.

-- It seems there might have been a similar post before with a complex answer. Hopefully, this clarifies things and prompts a simpler solution. Fingers crossed!

Answer №1

Have you ever witnessed this in action before?

Consider exploring the option of using jQuery-UI's drag and drop functionality.

Note: It appears that it does indeed work. To get started, I recommend using this jsbin as a reference point: http://jsbin.com/deyovunaxe/2/edit

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

Retrieve data from an array within the user Collection using Meteor and React Native

I need assistance with retrieving the entire array [votes] stored within the User Collection. Below is the JSON structure { "_id" : "pziqjwGCd2QnNWJjX", "createdAt" : ISODate("2017-12-21T22:06:41.930Z"), "emails" : [ { "a ...

Updating a secondary state array is possible by modifying a JavaScript array with setState()

In my React application, there is a grid where names can be selected. When a name is chosen, the app retrieves corresponding data from a database and displays rows of information related to that particular name. Each row is represented as an object stored ...

Is it possible to eliminate the sticky class as you scroll down?

Check out this jQuery code I wrote to remove the sticky class while scrolling down: $(window).scroll(function (e) { if ($('.main_form_wrapper').length != 0) { var window_scroll = $(window).scrollTop(); console.log(window_scro ...

Retrieving the selected value from a select2 dropdown in PHP when paired with an input type text

I have implemented multiple select2 dropdowns on my webpage to facilitate sending emails to users. One dropdown is for selecting recipients in the To field, and the other is for selecting recipients in the CC field. I want to ensure that when a user is sel ...

Cease the insertion of unknown characters into the react input

Is there a way to detect which character is being pressed on the keyboard using the onKeyDown event listener, and specifically how can I prevent the ',' from being inserted into the input element? const [inputValue, setInputValue] = useState("") ...

The body-parser module in express 4.0 is currently not accessible for the route handler

I am attempting to send a PUT request via Google Postman in the following format: PUT /updateUser/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="debcbcbc9eadadadf0bdb1b3">[email protected]</a> HTTP/1.1 Host: loca ...

"Utilize PHP to link to the same page, pass data through $_POST method, and

I have a database table containing (NumSection (id) and NomSection) In my webpage, I want to display all the data from 'NomSection' as a link. When clicked, I want to open the current page with $_POST['nomSection'] and show the data fo ...

Exploring the Information Within HTML Forms

When my HTML form sends data to the server, it looks like this: { r1: [ '1', '2', '3' ], r2: [ 'Top', 'Greg', 'Andy' ], r3: [ 'validuser', 'invaliduser', 'validuser&a ...

Floating and scrolling navigation bar not functioning properly in bootstrap framework

I've been dabbling in coding for a while now, practicing at my current job. I managed to create a floating and scrolling navigation bar on the right side of my website using bootstrap. However, after taking a 3-week break and returning to my site, I n ...

Utilize event delegation to retrieve the data attribute

Working great for me, able to access data-club-id: <!-- example --> <a class="clubCode" href="" data-club-id= "1234">join with the code</a> $("a.clubCode").on("click",function(e){ e.preventDefault(); var clubId = $(this) ...

What functionality does the --use-npm flag serve in the create-next-app command?

When starting a new NextJS project using the CLI, there's an option to use --use-npm when running the command npx create-next-app. If you run the command without any arguments (in interactive mode), this choice isn't provided. In the documentati ...

Experience the power of TypeScript in a serverless environment as you transform your code from

I have some JavaScript code that needs to be converted to TypeScript. Currently, I have two files: API_Responses.js const Responses = { _200(data = {}) { return { statusCode: 200, body: JSON.stringify(data), }; } }; module.export ...

What exactly is the significance of the </< in THREE.Camera.prototype.lookAt</<()?

After experimenting with THREE.js for a while, I came across something peculiar: When using Firefox and opening the developer console to type camera.lookAt (assuming your camera is named camera), it displays function THREE.Camera.prototype.lookAt</< ...

Dynamic styling with jQuery input focus animation

Whenever I interact with the input field, I want my border colors to animate in and fade out smoothly. But I'm facing some challenges. Here is how I've set it up: HTML <input type="text" id="search-input" placeholder=&quo ...

_background-variant.scss takes precedence over background color styling

I am currently working on an Angular 8 application that utilizes Bootstrap for styling. However, there seems to be a file called _background-variant.scss in Bootstrap that is overriding the background color of my menu, and I do not want this to happen. . ...

Error encountered while accessing a JSON object through jQuery that has been serialized on an ASP.NET .cs page

Hey there, I've been trying to run the code below by keeping it in a separate JavaScript file and referencing that file in all my .aspx files. Strangely enough, when I place this code directly in the script section of a .aspx file, it works perfectly ...

Crafting interactive image checkboxes

At present, the checkboxes in my application are quite basic with labels. However, our app designer has requested that we revamp this feature and make it more appealing by using clickable images that still function like checkboxes. Allow me to provide an ...

Experimenting with jQuery's .hide() and .show() functions with an alert message confirming that the div is not

Below is some simple code to demonstrate an issue: $('.myDiv').click(function() { $('.anotherDiv').hide(); alert('pause the ui'); $('.anotherDiv').show(); }); After clicking on the .myDiv element, the ...

What is the method for submitting a POST request with a JSON body that consists of only a string, without any key-value pairs included?

There was a developer who, not knowing the correct JSON format for key-value pairs, created a JSON body that looks like this: { "dog" } Instead of { "dog": "dog" } I must send the request from a JavaScript file, and the body needs to be in JSON f ...

Using AngularJS to showcase the quantity of table elements

On a web page, I am showcasing the number of table items as 20/67, denoting that "20" is the current items displayed and "67" is the total objects in the array. HTML <tr ng-repeat="mydata in data | startFrom:(currentPage - 1) * pageSize | linitTo: pag ...