rearranging the sequence of buttons using JavaScript

I am faced with the challenge of making a series of buttons draggable and droppable within a parent div without using any external libraries at the request of the client. Although I could have easily accomplished this task with jQuery, it's an opportunity to learn more basic concepts.

How can I achieve this? One complication is that the buttons are positioned inside a draggable parent div, requiring careful positioning, likely limited to relative positioning only.

If you have any ideas or suggestions on how I can tackle this problem, I would greatly appreciate it. Thanks in advance!

Answer №1

Peter-Paul Koch shared valuable insights in an informative tutorial about drag and drop functionality. While working on my own project, I suddenly recalled this resource and decided to quickly put together a demonstration in JSFiddle.

function makeElementDraggable(draggable, container){
    // If no container is specified, default to the window
    var container = container || window;
    
    var dragging = false;

    function handleDrag(moveEvent){
        moveEvent.preventDefault();

        dragging = true;

        var coordinates = [
            moveEvent.clientX,
            moveEvent.clientY
        ];

        var styleValues = {
            position: 'absolute',
            left: coordinates[0] + 'px',
            top: coordinates[1] + 'px'
        };

        for(property in styleValues){
            if(styleValues.hasOwnProperty(property)){
                draggable.style[property] = styleValues[property];
            }
        }
    }

    function handleDrop(upEvent){
        if(dragging === true){
            upEvent.preventDefault();

            container.removeEventListener('mousemove', handleDrag, false);
            draggable.removeEventListener('mouseup', handleDrop, false);

            dragging = false;
        }
    }

    draggable.addEventListener('mousedown', function startDrag(downEvent){
        downEvent.preventDefault();

        container.addEventListener('mousemove', handleDrag, false);
        draggable.addEventListener('mouseup', handleDrop, false);
    }, false);
}​ 

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

Despite receiving a return false from the Ajax verification, the form is still submitted when using onsubmit

I have implemented form verification using ajax to check for duplicate usernames. If a duplicate username is found, the function returns false; otherwise, it returns true. Below is the ajax code: function checkform(){ var username = $("#username").va ...

Struggling to pass along the URL value from a promise to various modules within Express is proving to be quite a challenge for me

I've been working on an app using ngrok, following a guide from Phil on setting up ngrok with nodemon. You can find the link to the post here. I need to have access to the URL received from the promise in the bin folder throughout the app server so t ...

What is the hostname that npm install directs to?

My task is to set up multiple Node.js packages using npm on a standalone server that does not have direct internet access. I am able to specify an IP Address and port for access. When executing 'npm install' from the command line, where can I f ...

Issue with Material UI dropdown not selecting value on Enter key press

I have encountered an issue with the material UI dropdown component that I am using. When I navigate through the dropdown options using arrow keys and press enter, the selected value does not get highlighted. Below is the code snippet for the dropdown: ...

Issues with table formatting and malfunctioning functions

I created a basic tic-tac-toe game, but I'm having an issue with the table display. It appears squished when the game loads. Is there a way to prevent this and keep the table empty? Additionally, I am using NotePad++ and encountering problems running ...

The 8 x 8 grid I am constructing is functional, however, the issue lies in the fact that the first line only begins with a single # symbol

I am attempting to create an 8 x 8 grid. It's coming together, but the issue is that the first line only starts with one # sign. function print(msg) { console.log(msg); return msg; } let result = ""; for(let i=1; i<=8; i++) { result += ...

unable to display data through the web service

The functionality of this code is correct, but it seems to not be displaying records. When the record is retrieved from the file and shown in an alert, everything works fine. $j().ready(function(){ var result =$j.ajax({ ...

What is the best way to ensure that the maximum price is mandatory when entering a minimum price?

Essentially, the process works like this: if a person inputs a minimum price but forgets to input a maximum price, then presses search, it will not perform the search and a message will appear next to the max price field reminding them to enter a maximum ...

Is there a way to retrieve the width of the parent element in ReactJS from a child component?

The issue has been fixed: I forgot to include .current in my ref... I am trying to determine the width of the element that will hold my component. I came across a solution on SO, but unfortunately it did not work for me as it returned undefined: import R ...

Ways to delay the inner function's output?

Need help with making a function return only after its inner function is called. See below for the code snippet - function x() { function y() { // Inner function logic } return result; // This should be returned only after function y is ca ...

Missing callback pattern in NodeJS

When I spend hours writing NodeJS code, there's a common scenario that leaves me unsure of how to proceed. Take the following async function call (where we forget the necessary callback): function foo (callback) { // Perform a task and call callba ...

Using async/await with Middleware in Express

I'm struggling to grasp the concept of writing middleware in Express that uses async/await without leaving a floating Promise after execution. Despite reading numerous blogs and StackOverflow posts, it appears that there is a common pattern for utiliz ...

Exploring the Use of 7BitEncodedInt in JavaScript

Currently, I am trying to read a binary file using JavaScript. It appears that this file may have been written in C#, which handles strings differently from how it's done in the source mentioned at https://learn.microsoft.com/en-us/dotnet/api/system. ...

What is the method for renaming Props in Vue components?

I recently embarked on my VueJS journey and attempted to implement v-model in a component, following an example I found. <template> <div class="date-picker"> Month: <input type="number" ref="monthPicker" :value="value.month" @in ...

How can I retrieve an image from a library and automatically update the image in SharePoint every 30 seconds?

I have a web part and I have written the code below: However, it is only fetching one image. How can I fetch all images from the library and change the image every 30 seconds using JavaScript or jQuery? public class MSDN : System.Web.UI.WebControls.WebPa ...

Guide for creating a CORS proxy server that can handle HTTPS requests with HTTP basic authentication

For my http requests, I've been utilizing a CORS-Proxy which works well for me. However, I recently stumbled upon an API for sending emails which requires http basic authentication for https requests. I'm uncertain of how to go about implementing ...

Comparing ng-transclude usage: element or attribute styling

Creating a wrapper directive to frame a notification widget within a list is my goal. I plan to transclude specific content based on a property from the 'notif' object into this frame. Currently, I have hardcoded a 'div' element. The i ...

Leveraging Nextjs Link alongside MUI Link or MUI Button within a different functional component (varieties)

Currently in my development setup, I am utilizing Next.js (10.2) and Material-UI (MUI) with Typescript. In the process, I have implemented a custom Link component: Link.tsx (/components) [...] On top of that, I have created another iteration which functi ...

Collaborate on global functions across the Quasar ecosystem and beyond, including Vue3

Is it plausible to utilize this method for sharing functionality (not data, which is handled by stores) in a Quasar and Vue3 application? // boot/generic_stuff.js import {boot} from 'quasar/wrappers' const function_list = { /* content goes here ...

Managing and updating arrays in VueJS2: Conditionally push new items and update only if their properties have changed

I am currently facing an issue with my form where each time a user updates a value in an input field, a new array element is created and added to the form results. I'm looking for a way to update the properties of the existing array element without cr ...