Search code examples
javascriptjquerypositiondraggableeach

Get the positions of multiple elements


I am trying to get the individual positions of multiple draggable elements using jQuerys .position and .each functions.

This is what i have so far...

JS

function newAppDraggable() {
    $('.App').draggable({
        containment: "#AppBox",
        grid: [ 60, 60 ],
        stack: ".App"
    });
};

$(function() {
    $('.AppList').droppable({
        accept: ".App",
        tolerance: 'fit',
        drop: function(event, ui) {
            $(".App").each(function( index ) {
            var position = $(this).position();
            var posTop = position.top;
            var posLeft = position.left;
            $( "#posThis" ).html(index+":"+posTop+":"+posLeft);
            });
        }
    });
});

HTML

<div class="AppList">
    <div id="TimenDate" class="App Fixed Size110x350">
    </div>

    <div id="User" class="App Fixed Size110x290">
    <p id="posThis"></p>
    </div>

    <div id="Weather" class="App Fixed Size110x350">
    </div>
</div>

Here is a fiddle for better explanation. On the fiddle the index stays at 2 and the positions only change when the 3rd app is moved.

what I would like is to be able to get the positions of all the individual apps and possibly save them in an array in a cookie (or something of the sort) so that i can reload them in their last positions when the page is refreshed.


Solution

  • In vanilla javascript and on modern browsers that support element.getBoundingClientRect

    Both of the following examples have been modified to demonstrate how the attained positions of each element can be added to an array that can then be accessed later.

    You could get the position information with this technique.

    var apps = document.querySelectorAll(".App"),
        positions = [];
    
    Array.prototype.forEach.call(apps, function (app, index) {
        var positionInfo = app.getBoundingClientRect();
    
        positions.push(positionInfo);
        console.log(index + ":" + positionInfo.top + ":" + positionInfo.left);
    });
    
    console.log(positions);
    

    On jsfiddle

    In the above example the browser must also have support for Array.forEach and document.querySelectorAll

    Using jquery, it would be something like this, using jQuery selectors, jQuery.each and jQuery.position

    var apps = $(".App"),
        positions = [];
    
    $.each(apps, function (index, app) {
        var positionInfo = $(app).position();
    
        positions.push(positionInfo);
        console.log(index + ":" + positionInfo.top + ":" + positionInfo.left);
    });
    
    console.log(positions);
    

    on jsfiddle