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

Consolidate and then transfer to a different database

How can I insert the data returned from my aggregate (controller function) into another collection called User? Here is the schema for the User: const userSchema = new mongoose.Schema({ firstName: { type: String, required: [true, &ap ...

Issue with Google Finance JSON response not functioning as expected in Chrome and Firefox browsers, yet appears to be working properly in

I am currently working on a JavaScript project that involves fetching STOCK data from the Google Finance API. When I manually paste the link into my browser, I can successfully retrieve the JSON response: // [ { "id": "22144" ,"t" : "AAPL" ,"e" : "NASDAQ ...

tips for optimizing javascript file caching

https://i.stack.imgur.com/UhWD1.pngMy web application was created using "pug" technology about 9-8 years ago, and more recently, pages have been added in an innovative framework (vue.js). However, whenever there is a transition between an old pug page and ...

Guide on retrieving a value from a function that invokes $.getJSON

function searchAndRetrieve(searchTerm) { var defaultResult = 1010; var resultValue = defaultResult; $.getJSON(remote, function(data) { if (data != null) { $.each(data.items, function(i, item) { ...

What is the best way to deactivate the time-based trigger in an old version of a Google sheet, while ensuring it remains active in the duplicated new version?

When I initially copied a Google Sheet, I assumed that the app scripts would be duplicated as well. However, it turns out that this is not the case. Here's the background story: I made a version 2 by copying version 1. Because I wanted to ensure that ...

Automatically switch tabs upon pressing/scanning the Return key (using PHP, MySQL, and JavaScript)

Seeking assistance to resolve an ongoing issue that has been troubling me for the past few weeks. I am maintaining a basic web-based database to keep track of product serial numbers leaving our warehouse. The system is secure behind our firewall, so I&apo ...

Exploring the power of the cssContainingText locator feature in Protractor

Currently working on a framework utilizing Protractor, I encountered an issue with the cssContainingText locator from the Protractor API. The locator threw an invalidElement exception, which puzzled me. The structure of the HTML page appears as follows: ...

Creating a list in React and adding a delay using setTimeout() method

I'm a beginner when it comes to working with React and I've been attempting to display a list of posts using a JSON array. My goal is to have the list render after a certain number of seconds, but for some reason, the list isn't rendering us ...

Parsing and Displaying JSON Data from a Python DataFrame in D3

Trying to create a stock chart, I encountered an issue with parsing the json file output by my python dataframe. The example code from http://bl.ocks.org/mbostock/3884955 does not seem to fit the format of my data: The json looks like this: var dataset = ...

Using brush strokes to create a unique design on the canvas page

Currently, I am working on implementing a brush-like effect on a web page. The task involves providing multiple patterns/textures in the background and allowing users to drag their mouse to create the pattern effect on the page. If you want to see the st ...

Deciphering HTML encoding for text fields

As I transition from the Microsoft stack, specifically WPF, to HTML5, I apologize for any beginner-level questions. Today's topic is HTML encoding and decoding. Imagine an HTML5 application making AJAX calls to a C# backend using HTTP. The server al ...

Encountering an issue with executing Google API Geocode in JavaScript

I'm having trouble printing an address on the console log. Every time I run the code, I encounter an error message that reads: { "error_message" : "Invalid request. Missing the 'address', 'components', 'latlng' or &ap ...

Best practices for refreshing the HTML5 offline application cache

My website utilizes offline caching, and I have set up the following event handler to manage updates: applicationCache.addEventListener('updateready', function () { if (window.applicationCache.status == window.applicationCach ...

Prevent Cross-Site Scripting attacks in Laravel by sanitizing user input, even when allowing HTML tags

What measures can be taken to protect against XSS attacks when a user is allowed to use HTML tags, such as in a textarea element? Avoiding the stripping or escaping of all tags complicates the situation and rules out the option of using {{ }}. It's a ...

The content within the tab is currently being loaded

Incorporating jQuery UI tabs into my webpage, I encounter a delay of 5-6 seconds when clicking on a tab as it triggers an ajax call for preparing and displaying content. The screen stays idle during this time, leading to user confusion. I am seeking a sol ...

JavaScript array as a reliable data storage solution

This is my unique jsp code where I am attempting to push certain data into a JavaScript array. <% int proListSize = proList.size(); ProfileDAO proDAO = null; for(int i = 0, j=1; i < proListSize; i++){ proDAO = ( ...

Use JavaScript to swap out images

How can I change the image arrow when it is clicked? Currently, I have this code snippet: http://codepen.io/anon/pen/qEMLxq. However, when the image is clicked, it changes but does not hide. <a id="Boton1" class="button" onClick="showHide()" href="j ...

What is the best way to ensure that custom JavaScript and CSS files in Sphinx are always loaded with the most recent changes

Within the configuration file conf.py for Sphinx, I have specified the following: html_css_files = ['css/custom.css'] html_js_files = ['js/custom.js'] However, any alterations made to custom.js or custom.css do not immediately appear i ...

Discovering the quantity of identical elements within a JavaScript array

Looking for some assistance in solving a JavaScript problem as I am relatively new to the language: I have an array and I need help in determining the count of identical values. Below is my array: var arr = ["red", "blue", "green", "red", "red", "gray"] ...

Teach me how to utilize Import / require() in Static Folder

I've been attempting this task for a while, but I'm unsure how to incorporate import or require into the express static folder. When I try to use it, I receive an error stating "require not defined" which makes sense since these are not supported ...