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

Angular 8: ISSUE TypeError: Unable to access the 'invalid' property of an undefined variable

Can someone please explain the meaning of this error message? I'm new to Angular and currently using Angular 8. This error is appearing on my console. ERROR TypeError: Cannot read property 'invalid' of undefined at Object.eval [as updat ...

Combining two objects with JQuery while preserving all their properties

I am attempting to combine/merge two objects together. Currently, I have the following: var mergeObj = {}; var obj1 = { name: 'abd', id: 5454756, color: 'red' } var obj2 = { name: 'abc1', id:387589, color: 'blue'} I ...

Using JavaScript to retrieve data from a JSON file and showcase it on a jQuery mobile webpage

I am struggling to retrieve JSON data from a PHP URL using JavaScript and display it within a JQuery mobile "li" tag as a category list. Despite spending the last 8 hours on it, I can't seem to get it working using the code provided below. Any help wo ...

Using Selenium 2 to dynamically insert CSS styles into the currently visible webpage

I experimented with using jQuery on a webpage that has already been modified by jQuery in order to add custom CSS code: jQuery('head').append('<style type=\"text/css\">body { background: #000; }</style>'); When I ...

When utilizing an object as state in React, the `setState` function will only set

Currently, I am working on developing a React form that utilizes a custom Input component which I have created multiple times. The objective is to gather all the names and values from the form in the parent component: {inputName: value, inputName2: valu ...

Most effective method to retrieve yesterday's data

Currently, I'm working on a requirement and I need to validate the logic that I've implemented. Can someone help me with this? The task at hand is to calculate the 1 month, 3 month, and 6 month return percentages of a stock price from the curren ...

Enhancing Promises.all with extra parameters

Looking to dive into promises, eager to learn. Here is an array of shopIds I'm working with: let shopIdsArray = ['shop1','shop2','shop3']; Additionally, there's an external promise call: getProducts(shopId, ' ...

Surrounding the text with background color

My H1 text is in a div that spans multiple lines due to the fixed width of the div. I am looking to set the background color to only appear behind the actual text of the H1, without extending into empty space at the end of each line. In addition, I also n ...

How can I combine various array values of equal length using a delimiter to create one final array?

I am trying to combine the values from 3 separate arrays, all of which have the same length. var title = ['title 1','title 2','title 3']; var description = ['description 1','description 2','descri ...

AJAX Post Request Function without Form That Does Not Reset

I am currently struggling with understanding the Ajax POST method. I am attempting to make an API request, and since the response has similar parameters, I decided to create a global function that can be used by other HTML/JS pages. However, I am aware tha ...

What is the best way to line up a number and text using CSS?

Creating a basic gauge meter with min value 0 and max value 2. The current UI progress is as follows: .sc-gauge { width:200px; height:200px; margin:200px auto; } .sc-background { position:relative; height:100px; margin-bottom:10px; background-color:g ...

I'm trying to set an object value for this select element, and while I have managed to do so, I am struggling to display the title of the selected object. Can anyone help me

I am struggling to display the title of the selected object in this select element. Can anyone help me understand why my code is not showing the title? Here is the code snippet: const [selectedCategory, setSelectedCategory] = useState(""); const categor ...

Issue in IE with click event not firing from parent page

Currently, I am facing an issue with a filter on one of my website's pages that is designed to display various products. My goal is to set it up so that when a button from an external page is clicked, the user will be redirected to the product page wh ...

Ways to adjust the distance between logo and slider

I am using this script to showcase some products. You can find the script at: http://tympanus.net/Tutorials/ItemSlider/ When resizing the web browser from maximum size to smaller, I find that the height between the logo and shoes is too large for my likin ...

The React app I've been working on has a tendency to unexpectedly crash when reloading the code from time

Dealing with a frustrating issue here. I've been working on an app and for the past few weeks, it keeps crashing unexpectedly. It seems to happen more frequently after saving my code to trigger a reload, but it can also just crash randomly while navig ...

Error: Loop Program Encountered Unexpected Token Syntax

Every time I attempt to run this code, a syntax error (unexpected token) appears. As someone who is still learning JavaScript, I am struggling to identify the root cause of this issue. var x = 1; var example = function(){ for(var y = 0; y < ...

Tips for retrieving all values included in the <tr> tags within an html <table>

When the checkbox in the fourth column is clicked, I would like to retrieve all values of td. Additionally, I want to determine the smallest value between ID and Optional ID. <table><form method='GET'> <tr> <th>Name</t ...

Clearing up memory in ThreeJS application

I'm facing challenges with memory management in my ThreeJS application. I know there are already a few queries regarding this issue: freeing memory in three.js Freeing memory with threejs Three.js Collada - What's the proper way to dispose() a ...

How to apply unique styles to multiple elements with the same class using jQuery?

How can I add different classes to multiple div elements with the same class based on their content? <div class = "flag"> Yes </div> <div class = "flag"> No </div> <div class = "flag"> Yes </div> <div class = "flag"& ...

Displaying or concealing dropdown menus based on a selected option

My goal is to have a drop-down menu in which selecting an option triggers the display of another drop-down menu. For example, if I have options like "Vancouver," "Singapore," and "New York," selecting Vancouver will reveal a second set of options, while ch ...