Preserve the location of a moveable div using jQuery

I have implemented draggable divs in my JSP page, allowing users to move them around freely. After dragging the divs, I would like to save their positions either in a cookie or database for future reference. Could you please advise on the best way to achieve this? Below is the code snippet of my draggable implementation:

<div id="drag">
    <div>
        <div>
            <div>
                This div is draggable
            </div>
        </div>
    </div>
</div>

<script type="text/javascript'>
    $(document).ready(function () {
        $('#drag').draggable();
    })
</script>

Answer №1

If you want to preserve the X/Y coordinates, you can store them in various ways. Whether it's local storage, cookies, or an API, the method doesn't matter as long as you capture the information.

<div id="drag">
    <div>
        <div>
            <div>
                <p>This div is draggable</p>
                <button id="saveMe">Save</button>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
$(document).ready(function () {
    if (local.get('divOffset')) {
        //check if local storage already has your offset. and set it
        $('#drag').css(local.get('divOffset'))
    }

    $('#drag').draggable();

    $('#drag').on('click', '#saveMe', function () { 
        // we're listening for a click event on the saveMe button
        var $drag = $('#drag'),
        //assigning the #drag div jQ obj to a variable
            offset = $drag.offset(); 
        // grabbing the offset: Object {top: 157.5, left: 150}
        local.set('divOffset', offset);
        //save the offset(local storage)
    });

});

function Local () {
    return {
        set : function (key, obj) {
            localStorage.setItem(key, JSON.stringify(obj));
            return obj;
        },
        get : function (key) {
            var obj = {};
            if (localStorage.getItem(key) !== 'undefined') {
                obj = JSON.parse(localStorage.getItem(key));
            }
            return obj;
        },
        clear : function () {
            localStorage.clear();
            return this;
        },
        remove : function (key) {
            localStorage.removeItem(key);
            return this;
        }
    };
}
var local  = Local();

</script>

Storing data in a database via an API ensures consistency across multiple devices, unlike local storage which is tied to a single machine. I have showcased local storage here for illustration purposes, but using an API for saving data is a more complex process.

Below is a custom getter/setter function I created for local storage management in the past.

Answer №2

  • Check out this amazing jQuery cookie plugin that you can utilize:

https://github.com/carhartl/jquery-cookie

  • Take a look at this example using jquery and php for storing data in a database.

  • Here is a functional demonstration with the jquery plugin storing data as cookies.

JS

jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', 
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

//------------------------------------------------END of plugin!---------------------------------
$('div:first').draggable({
   stop: function(event, ui) { 
       $.cookie('div1x', $(this).css('left'));
       $.cookie('div1y', $(this).css('top'));
       }
});
$('div:last').draggable({
   stop: function(event, ui) { 
       $.cookie('div2x', $(this).css('left'));
       $.cookie('div2y', $(this).css('top'));
       }
});
if($.cookie('div1x') != null){
    $('div:first').css('left', $.cookie('div1x'));
}else{
    $('div:first').css('left', '50px');
}
if($.cookie('div1y') != null){
    $('div:first').css('top', $.cookie('div1y'));
}else{
    $('div:first').css('top', '100px');
}
if($.cookie('div2x') != null){
    $('div:last').css('left', $.cookie('div2x'));
}else{
    $('div:last').css('left', '150px');
}
if($.cookie('div2y') != null){
    $('div:last').css('top', $.cookie('div2y'));
}else{
    $('div:last').css('top', '250px');
}
div
{
    width:100px;
    height:100px;
    background-color:cyan;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.min.js"></script>

<div></div><div></div>

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

Validation of AngularJS dropdown selection must be completed before submitting the form

I have a Dropdown list within my form and I want to disable the submit button until an element is selected from the list. Here is my button: <input type="submit" value="Get" ng-disabled="form.$invalid " /> I attempted to implement the solution foun ...

focusing on a specialized format using the serialize() method

Following up on my previous question which was answered so promptly by Meder, there is now an additional query that has arisen while creating a reusable jQuery form submission without redirecting the user. Issue The jQuery serialize() function is applyin ...

I was unable to produce the result of the input value entered at the bottom

Is there a way to view the input and output simultaneously in my project? I've seen this done using a button, but I'm looking to achieve the same without a button. How can I do this? <input type="text" id="myText"> <b ...

You do not have permission to access the restricted URI, error code: 1012

What is the best solution for resolving the Ajax cross site scripting issue in FireFox 3? ...

"When a Vuex mutation modifies the state, the computed property fails to accurately represent the changes in the markup

I've encountered a perplexing issue with using a computed property for a textarea value that hasn't been addressed in a while. My setup involves a textarea where user input is updated in Vuex: <textarea ref="inputText" :value="getInputText" ...

Problem with styling a CSS table

I am having an issue with the table style. My goal is to set the table radius to 8px, but my code doesn't seem to be working. Can someone assist me with this? Thank you! //ps I also require border-collapse in my code. Here is the link to my jsfidd ...

Tips for coordinating the use of the '.append()' method and an ajax request within a loop

Greetings, everyone! I am facing a challenge with asynchronous actions that I cannot seem to resolve. I was expecting the following output: Category 1, Items of category 1 Category 2, Items of category 2 Category 3, Items of category 3 However, wha ...

"Utilize PrimeNG's p-tabpanel to bind a unique style class to

When using the tabview component from PrimeNG, I am encountering an issue where I am unable to bind a header style class. Here is my static HTML code that works: <p-tabPanel header="Title" headerStyleClass="badge" formGroupName=&quo ...

Navigating the authorization header of an API request in a Node environment

const authHeader = req.headers["authorization"]; I have a question that may come across as basic - why do we use ["authorization"] instead of just .authorization? After some research, I discovered it had to do with case sensitivity but ...

The issue with calling Ajax on button click inside a div container is that the jQuery dialog box is

Here is the code for my custom dialog box: $("#manageGroupShow").dialog({resizable: false, draggable: false, position:['center',150], title: "Manage Group", width:"50%", modal: true, show: { effect:"drop", duration:1000, direction:"up" }, hide: ...

Using React to create a fadeout effect and decrease the length of the photo

Is there a way to create a fade-out effect for each photo card and then shorten the length of the photos following the fade out? I have tried implementing a solution, but it doesn't seem to work when I click on each photo. Any suggestions or insights ...

Eliminate JSON data that pertains to dates that are either in the past or future

I am working on integrating upcoming classes and past classes components into my application. I have successfully stored the schedule of classes and can retrieve them using backend services. However, I need to display only the upcoming classes in one compo ...

Filtering JSON data by date range in React JS

I have a dataset with JSON data containing ISO dates, and my goal is to filter out entries based on the "date_created" field falling within a specific date range. The time component should be ignored in this comparison, and the original JSON data should re ...

The d3 drag functionality is only active when the axis ticks are selected

Currently, I am developing a unique package that combines Angular and D3 (v3) and my main focus is on integrating D3's dragging feature into the package. Although I am very close to achieving success, there is a minor bug that I need to address. When ...

Use column formatting for the table's body section

I have written the code below in HTML to create a table. I am looking to apply a specific style to the table body elements in a column that has been assigned a CSS class, while excluding the header columns from this style application. As an example, I hav ...

organize divs in a nested angular style

Looking to showcase div elements in a specific layout within my Angular project: https://i.sstatic.net/RH0lF.png The current HTML structure is as follows: <div class="outer-wrapper"> <div class="image" ng-repeat="image in images" ng-if="sho ...

Showcase -solely one property object- from numerous property objects enclosed within an array

Hello, I am seeking assistance as I have recently begun learning about angularJS. I am working with objects that have keys such as: scope.eventList=[]; for(){ var event = { id : hash, ...

Regular expression for selecting characters and numbers in jQuery using a selector

Can someone help me figure out how to select all IDs like this: r1 r2 r3 etc. and not the other IDs like helloWorld I attempted using the CSS selector with jQuery but I'm having trouble understanding how. I tried $('#r[0-9]') but it didn& ...

Printing long contents on Chrome's ion-modal-view is not supported on every page

I have tried various solutions found in articles but have not been successful. Here is an example of one such attempt: @media print { .modal { position: absolute; left: 0; top: 0; margin: 0; padding: 0; visibility: visible; / ...

Customize the progress bar color in Bootstrap by setting a unique color to it

Is it possible to apply a custom color to the progress bar in Bootstrap that is not one of the standard options like success, info, warning or danger? I attempted adding the following code snippet to my bootstrap-theme.css file: .progress-bar-custom { b ...