Maintain the previous droppable positioning after refreshing the page

I am encountering an issue with the .droppable event. I have set up two sections where I can move elements, but every time the page is refreshed, the positioning of the elements reverts to the initial position. How can I maintain the last positioning of the elements even after a page refresh?

Sample: http://jsfiddle.net/jhogervorst/CPA5Y/

HTML:

<div class="group">
    <h1>Group 1</h1>

    <ul class="parent">
        <li class="droppable"><span class="draggable">Item 1</span></li>
        <li class="droppable"><span class="draggable">Item 2</span></li>
        <li class="droppable"></li>
    </ul>
</div>

<div class="group">
    <h1>Group 2</h1>

    <ul class="parent">
        <li class="droppable"><span class="draggable">Item 3</span></li>
        <li class="droppable"></li>
        <li class="droppable"><span class="draggable">Item 4</span></li>
    </ul>
</div>

CSS:

* { margin: 0; padding: 0; }
body { font-family: Helvetica, Arial, sans-serif; }
h1 { font-weight: bold; margin-bottom: 10px; }

.group {
    width: 150px;
    margin: 5px 0 5px 5px;
    float: left;
}

.parent {
    list-style-type: none;
}

.parent li {
    height: 41px;
    margin-bottom: 5px;
    padding: 5px;
    background: #ddd;
}

.parent li.active {
    background: yellow;
}

.parent li.hover {
    background: orange;
}

.parent li.hover span {
    opacity: .5;
}

.parent li span {
    display: block;
    height: 25px;
    line-height: 25px;
    padding: 5px;
    background: #eee;
    border: 3px solid #eee;
    cursor: move;
}

.parent li span.ui-draggable-dragging {
    z-index: 10;
    border-color: red;
}



$(".draggable").draggable({
    revert: true,
    revertDuration: 0
});

jQuery:

$(".droppable").droppable({
    activeClass: "active",
    hoverClass: "hover",

    accept: function (draggable) {
        // The droppable (li element).
        var droppable = $(this);

        // The droppable which contains the draggable, i.e., the parent element of the draggable (li element).
        var draggablesDropable = draggable.parent();

        // Is the draggable being dragged/sorted to the same group?
        // => We could just sort it, because there's always enough space inside the group.
        if (droppable.parent().is(draggablesDropable.parent())) {
           return true;
        }

        // Nope, the draggable is being dragged/sorted to another group.
        // => Is there an empty droppable left in the group to which the draggable is being dragged/sorted?
        else if (droppable.parent().find(".draggable").size() < droppable.parent().find(".droppable").size()) {
            return true;
        }

        // Nothing true?
        return false;
    },

    drop: function(event, ui) {
        // The droppable (li element).
        var droppable = $(this);

        // The draggable (span element).
        var draggable = ui.draggable;

        // The droppable which contains the draggable, i.e., the parent element of the draggable (li element).
        var draggablesDropable = draggable.parent();

        // Is the draggable being dragged to it's own droppable?
        // => Abort, there's nothing to drag/sort!
        if (droppable.is(draggablesDropable)) {
            return;
        }

        // Is the draggable being dragged to an empty droppable?
        else if (!droppable.find(".draggable").size()) {
            // Just drop the draggable there.
            droppable.append(draggable);
        }

        // Is the draggable being dragged/sorted to the same group?
        // => We can just sort it, because there's always enough space inside the group.
        else if (droppable.parent().is(draggablesDropable.parent())) {
            // Is the draggable being dragged up?
            if (droppable.parent().find(".droppable").index(draggablesDropable) > droppable.parent().find(".droppable").index(droppable)) {
                // Add the dragged draggable's droppable before the droppable.
                draggablesDropable.insertBefore(droppable);
            }

            // No, the draggable is being dragged down.
            else {
                // Add the dragged draggable's droppable after the droppable.
                draggablesDropable.insertAfter(droppable);
            }
        }

        // Nope, the draggable is being dragged/sorted to another group.
        // => Is there an empty droppable left in the group to which the draggable is being dragged/sorted?
        else if (droppable.parent().find(".draggable").size() < droppable.parent().find(".droppable").size()) {
            // Find the first empty droppable in which the draggable is being dragged/sorted.
            var emptyDroppable = $($.grep(droppable.parent().find(".droppable"), function (item) {
                // Are there draggables inside this droppable?
                // => Return TRUE if not.
                return !$(item).find(".draggable").size();
            })).first();

            // Clone the dragged draggable's droppable before itself, because we need to remember its position after moving it.
            var draggablesDropableClone = draggablesDropable.clone().insertBefore(draggablesDropable);

            // Is the draggable being dragged above the empty droppable?
            if (droppable.parent().find(".droppable").index(emptyDroppable) > droppable.parent().find(".droppable").index(droppable)) {
                // Add the dragged draggable's droppable before the droppable.
                draggablesDropable.insertBefore(droppable);
            } else{
                // Add the dragged draggable's droppable after the droppable.
                draggablesDropable.insertAfter(droppable);
            }

            // Remove the position of the dragged draggable, as there may still be some residual CSS from the dragging.
            draggable.css({"top": 0, "left": 0});

            // Add the first empty droppable before the cloned draggable's droppable. Then remove the latter.
            draggablesDropableClone.before(emptyDroppable).remove();
        }
    }
});

Answer №1

Storing the position on the page is not supported. One option is to send the position to the server and save it there. Another alternative is to use a cookie to store the position.

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

Quiz application utilizing MySQL and JSP technology

I've been developing a Web Application using JSP to host MCQ quizzes. The questions are stored in a MySql Database table called 'qna', with each question having 10 choices. My goal is to design the quiz so that each question appears on a new ...

Adjust regex for image URLs in JavaScript to handle unique and special cases

Does anyone have experience with using image URL regular expressions to validate images in forms with the ng-pattern directive? I'm currently facing difficulties handling cases like https://google.com.png. Any assistance would be greatly appreciated. ...

The issue with ngFileUpload causing empty file posts on Safari

Currently, I am utilizing ngFileUpload to transmit images to the Cloudinary service. My application is constructed on Ionic and is meant to be functional on both iOS and Android platforms. The code snippet below showcases my image uploading process: .se ...

Tips on reversing a numeric value with scientific notation in nodeJS

Exploring the optimal method to reverse an integer (positive and negative) in NodeJS 12 without the need to convert the number to a string. This solution should also accommodate numbers written in scientific notation such as 1e+10, which represents 10000 ...

What is the best way to invoke a function in one View Model from within another View Model?

I am looking to divide my DevExtreme Scheduler into two separate view models. One will be responsible for displaying the Scheduler itself, while the other will handle the Popup and button functionality. Despite having everything set up, I am struggling to ...

Refreshing the page in Next.js causes issues with the CSS classNames

I am currently in the process of migrating a React SPA to Next.js, and I am relatively new to this framework. The issue I am encountering is that when I initially load the Home page, everything appears as expected. However, if I refresh the page, incorrect ...

What's the deal with receiving [object Object] in my JavaScript JSON document?

When I use console.log(values), it returns "[object Object]" instead of logging the array as expected. This is the code snippet I'm working with: let values = { "coins": 0, "griffinFeathers": 0, "souvenir": 0, "cogs": 0, "cats": 0 ...

Retrieving data for a route resolver involves sending HTTP requests, where the outcome of the second request is contingent upon the response from the first request

In my routing module, I have a resolver implemented like this: { path: 'path1', component: FirstComponent, resolve: { allOrders: DataResolver } } Within the resolve function of DataResolver, the following logic exists: re ...

The disable button functions properly upon first use, but fails to work after it has been pressed once. What steps can I

CSS $(document).ready(function() { $("#inputGroupSelect02").change(function() { var str = ""; if ($("#inputGroupSelect02 option:selected").val() == '') { $('#button').attr('di ...

Looking for a solution to resolve the error in this SQL example?

I'm looking to extract node "-all_models=1-4.htm" in SQL using the example provided. Here is my current code: <div class="models_selector_block" > <DIV class="msb_item"> <a class="ser_active" hr ...

PHP fails to recognize Ajax POST requests

Here is a function I have created to submit forms: function submit_form(form) { $( form ).submit(function(e) { // Prevent form submission e.preventDefault(); // Get the form instance ...

Steps for incorporating buttons and input fields on a WordPress website

I recently customized an HTML block on my WordPress.com site and created a simple code snippet to function as a search widget. I've experimented with various approaches, such as attempting to trigger a script function with a button, making the functi ...

Embed a hyperlink within an informational passage

I have a search box with Ajax functionality like this; And I want to customize the NotfindText message to display as: "No results found, but you can try advanced search from here" However, I am struggling to add the link. I do not have much knowledge abo ...

"Encountering an Error with Route.get() when attempting to utilize an imported

I have a function that I exported in index.js and I want to use it in test.js. However, when I try to run node test, I encounter the following error message: Error: Route.get() requires a callback function but got a [object Undefined] What am I doing wro ...

Top strategies for creating a fully responsive HTML design

Currently, I am exploring the concept of responsiveness in my small projects for educational purposes. I have been researching websites such as: w3schools-mediaquery While I have come across some interesting insights, I am curious about how to effectivel ...

What is the best way to create a div that resembles a dotted line?

I have a bar chart type created using different div elements. CSS: .outer, .inner, .target { height: 14px; margin-bottom: 5px; } .outer { background-color: #cccccc; width: 200px; margin: 0 auto; position: relat ...

What is the best way to create and implement custom declaration files that are not available on @types or DefinitelyTyped?

I have encountered a situation where I am using an npm package named foo that is not available on DefinitelyTyped or may be outdated. Despite this, I still want to consume it under stricter settings like noImplicitAny, so I need to create custom definition ...

Activate the datepicker in Angular by clicking on the input field

This is my html file: <mat-form-field> <input matInput [matDatepicker]="picker" placeholder="Choose a date"> <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle> <mat-datepicker #picker></mat-date ...

Attempting to move elements into an array for storage in the local storage

Is there a way to properly add elements to an array and store it in localstorage? Here's the code snippet I've been working with: const handleSelectLayouts = (layout) => { const layoutsArray = []; layoutsArray.includes(layout) ...

Unable to access frame: Error - Unable to retrieve 'add' property from undefined

I am working on customizing the chatbot functionality for my website built with Nuxt.js. I want the chatbot to display on certain pages while remaining hidden on others. Unfortunately, I encountered an issue when trying to hide it on specific pages. To im ...