micheal
micheal

Reputation: 95

Save the position of a draggable div in jquery

I have some draggable divs in my jsp which i can drag all around the page.After dragging there is one save button,On click of which i want to save the positions of grid in cookie or database whichever solution is better.Please suggest how can i do that.Below is my draggable code

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

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

Upvotes: 4

Views: 6549

Answers (2)

Brian Noah
Brian Noah

Reputation: 2972

Basically you want to take the X/Y coordinates and save them. This can be to local storage, set a cookie, send it to an API, it doesn't matter. But this is how you get the info.

<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>

The good about saving it to a database through an API service is that a user could go from computer to computer and their info will stay the same. local storage will stay persistent only on one machine. I've included local storage in order to give one example, as saving to an API is MUCH more involved.

This is a local storage getter/setter function I wrote a long time ago.

Upvotes: 4

dbd
dbd

Reputation: 159

  • Here you have the jquery cookie plugin that you may use:

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

  • This is an example with jquery and php storing in a database.

http://code.tutsplus.com/tutorials/simple-draggable-element-persistence-with-jquery--net-7474

  • And here you have a working example with the jquery plugin storing 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() : '', // use expires attribute, max-age is not supported by IE
            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>

Upvotes: 0

Related Questions