Ensure that the assistant stays beneath the cursor while moving it

I am currently working on creating a functionality similar to the 'Sortable Widget', but due to some constraints, I cannot use the premade widget. Instead, I am trying to replicate its features using draggable and droppable elements:

$(".Element").draggable({
    helper: 'original',
    drag: function(event, ui) {

        ElementWidth = $(this).outerWidth(true);
        if($(this).prev().length){
            LeftElementWidth = $(this).prev().outerWidth(true);
            LeftElementLeftOffset = $(this).prev().offset().left;
            if(parseFloat(ui.offset.left+(ElementWidth/2)) < parseFloat(LeftElementLeftOffset+(LeftElementWidth/2)){
                $(this).prev().before($(this));
            }
        }

        if($(this).next().length){
            RightElementWidth = $(this).next().outerWidth(true);
            RightElementLeftOffset = $(this).next().offset().left;
            if(parseFloat(ui.offset.left+(ElementWidth/2)) > parseFloat(RightElementLeftOffset+(RightElementWidth/2)){
                $(this).next().after($(this));
            }
        }
    }
});

$("#Container").droppable({ accept: '.Element' });

The implementation works well, however, there is an issue where the draggable-helper does not stay under the mouse cursor when moving the element to the next position. You can see the problem in action by checking out this fiddle:

http://jsfiddle.net/5qFhg/15/

If you try sorting the green boxes, you'll notice the discrepancy. Is there a way to keep the helper in the correct position?

Answer №1

Check out this link for more information.

Does this align with your needs? Are you open to utilizing knockout? Unfortunately, I am unable to leave comments as my reputation is under 50.

<a href="#" data-bind="text: name, click: function() { viewModel.selectTask($data); },     visible: $data !== viewModel.selectedTask()"></a>
<input data-bind="value: name, visibleAndSelect: $data === viewModel.selectedTask(), event: { blur: function() { viewModel.selectTask(''); } }" />

Try using the parent and previous location to replicate the desired functionality.

ko.bindingHandlers.sortableList = {
init: function(element, valueAccessor, allBindingsAccessor, context) {
    $(element).data("sortList", valueAccessor()); //attach meta-data
    $(element).sortable({
        start: function(event, ui) {
            //track the original position of the element
            var parent = ui.item.parent();
            var prev = ui.item.prev();
            //create a function to move it back (if it has a prev sibling, insert after it, otherwise put it at the beginning)
            ui.item.moveItemBack = prev.length ? function() { ui.item.insertAfter(prev); } : function() { parent.prepend(ui.item); };
        },
        update: function(event, ui) {
            var item = ui.item.data("sortItem");
            if (item) {
                //identify parents
                var originalParent = ui.item.data("parentList");
                var newParent = ui.item.parent().data("sortList");

                //figure out its new position
                var position = ko.utils.arrayIndexOf(ui.item.parent().children(), ui.item[0]);

                if (position >= 0) {
                    //move the element back to its original position and let KO handle adding it to the new parent
                    if (originalParent !== newParent) {
                        ui.item.moveItemBack();
                    }

                    //place item in the proper position
                    newParent.remove(item);
                    newParent.splice(position, 0, item);
                }
            }
        },
        connectWith: '.container'
    });
}

Would you like the divs to be displayed next to each other?

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

Unable to locate the value property of a null object

I'm currently working on creating a Shopping Cart using HTML, CSS, JavaScript, and JQuery. The idea is that when you click "Add to Cart" for the orange item, most of the HTML elements will disappear, leaving only the table displaying the Shopping Cart ...

Looking to automatically dismiss a tooltip on mobile devices a few seconds after it's tapped

Here's an anchor tag with a tooltip: <a data-toggle="tooltip" data-original-title="Apologies, pronunciation audio is currently unavailable."> <span class="glyphicon glyphicon-volume-off pronounce"> </span> </a> When v ...

Exploring the assortment of reactions post-awaitReaction in node.js

The current code runs smoothly, but I encounter an issue when attempting to send messages after selecting either the X or check option. Instead of the expected outcome, I receive Despite my understanding that this collection is a map, all attempts to acce ...

next.js users may encounter a problem with react-table not rendering correctly

Encountering difficulties while attempting to integrate a basic table function into my upcoming application. Despite being a sample output, the function fails to load into the index for some unknown reason! // Layouts import Layout from "../components ...

Error encountered while running a mounted hook in Vue.js that was not properly handled

I have created a To Do List app where users can add tasks using a button. Each new task is added to the list with a checkbox and delete button next to it. I want to save all the values and checked information on the page (store it) whenever the page is ref ...

What steps can I take to ensure a JavaScript loading image is displayed until the entire page has finished loading?

Looking to implement a JavaScript loading image that displays until the page has fully loaded? I'm currently developing an online antivirus scanner and in need of help. I am trying to set up JavaScript to show a loading image while a file is being up ...

Prevent the Icon in Material UI from simultaneously changing

I'm working on a table where clicking one icon changes all icons in the list to a different icon. However, I want to prevent them from changing simultaneously. Any suggestions on how to tackle this issue? Code: import React from 'react'; im ...

Challenges with managing VueJS methods and understanding the component lifecycle

I'm facing an issue with my code. The function retrieveTutorials() is not transferring the information to baseDeDatosVias as expected. I've attempted to change the function to a different lifecycle, but it hasn't resolved the problem. The so ...

Pressing the enter key causes duplicate input fields in Internet Explorer

I am having an issue with my code snippet HTML <button id="add-input">add</button> <div id="input-container"></div> JS $('#add-input').on('click',function () { $('<input type="text">').app ...

Encountering a mistake due to the anticipated atom not being found at the specified

In my react application, I am encountering an issue with allowing foreign characters along with English in the input field of a form. I have implemented a regular expression as follows: const alphabetRegex = /^([A-Za-z]+ )+[A-Za-z]+$|^[A-Za-z]*\p{L}/g ...

Error occurred due to a reference to a function being called before it was

Occasionally, I encounter a "Reference Error" (approximately once in every 200 attempts) with the code snippet below. var securityPrototype = { init: function(){ /* ... */ }, encryptionKey: function x() { var i = x.identifier; ...

Exclude a specific tag from a div in JavaScript

I need help selecting the text within an alert in JavaScript, excluding the <a> tag... <div id="addCompaniesModal" > <div class="alertBox costumAlertBox" style="display:inline-block;"> <div class="alert alert-block alert- ...

Exploring the concept of next middle-ware within the realm of Express.js and Sail.js controllers

Currently, I am utilizing sails.js framework which is constructed on top of express.js. Within my routes.js file, I have defined a route as shown below: '/account/login': { controller : 'Session', action : 'l ...

Exploring the power of Nestjs EventEmitter Module in combination with Serverless functions through the implementation of Async

I am working on implementing an asynchronous worker using a serverless lambda function with the assistance of the nestjs EventEmitter module. The handler is being triggered when an event is emitted, but the function closes before the async/await call. I ...

What methods can be used to accomplish this effect using CSS and/or Javascript?

Is there a way to achieve the desired effect using just a single line of text and CSS, instead of multiple heading tags and a CSS class like shown in the image below? Current Code : <h2 class="heading">Hi guys, How can i achieve this effect using j ...

The landscape orientation causes the button bar to overflow by 100% of the body height

Imagine the scenario below: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <style type="text/css"> html, body { padding: 0; margin: 0; ...

Having trouble with AES decryption on my nodeJS/ExpressJS server backend

Looking to decipher data post retrieval from mongoDb. The retrieved data comprises encrypted and unencrypted sections. app.get("/receive", async (req, res) => { try { const data = await UploadData.find(); const decryptedData = data. ...

What is the best way to position a rectangle on top of a div that has been rendered using

I recently started using a waveform display/play library known as wavesurfer. Within the code snippet below, I have integrated two wavesurfer objects that are displayed and positioned inside div elements of type "container". My goal is to position my own ...

How can I search multiple columns in Supabase using JavaScript for full text search functionality?

I've experimented with various symbols in an attempt to separate columns, such as ||, |, &&, and & with different spacing variations. For example .textSearch("username, title, description", "..."); .textSearch("username|title|description", "..."); U ...

Connecting the value of one input to influence another input

There are two input boxes provided - one for current address and another for permanent address. When the checkbox is clicked, the value of the current address should be displayed in the permanent address box. However, I am facing an issue where when I unc ...