Steve Soares
Steve Soares

Reputation: 21

How to constantly find the x and y position of a moveable element

   $(function() {
    
    $.fn.getPosition = function() {
        var results = $(this).position();
        results.right = results.left + $(this).width();
        results.bottom = results.top + $(this).height();
        return results;
    }
    
    $(nWindow).resizable({
        maxWidth: 1356,
        maxHeight: 585.5,
        grid: [ 3, 4 ],
        aspectRatio:true,
        
    });

    $(nWindow).draggable({
        cursor: "move",
        snapTolerance: '20',
        snap:nWindow, 
        containment:container,
        stop: function(e, ui) {
         console.log($(this).attr("id"), $(this).getPosition()); //How do i store these positions into a variable and use it in other functions
        } 

});

In the above code, how do i store the values of this.getposition that is left and top into seperate variables so i could use it in other functions, i know i could do it by declaring a global variable and then assigning .getposition but i want to constantly keep a track of the div thats being moved and update the variable accordingly, when i assign the variable and try calling it it gives me nullor undefined

Upvotes: 0

Views: 107

Answers (1)

Ran Marciano
Ran Marciano

Reputation: 1531

try using it like this

let postion = {};
$(function() {
    
    $.fn.getPosition = function() {
        var results = $(this).position();
        results.right = results.left + $(this).width();
        results.bottom = results.top + $(this).height();
        postion = {...result}; 
        return results;
    }
    
    $(nWindow).resizable({
        maxWidth: 1356,
        maxHeight: 585.5,
        grid: [ 3, 4 ],
        aspectRatio:true,
        
    });

    $(nWindow).draggable({
        cursor: "move",
        snapTolerance: '20',
        snap:nWindow, 
        containment:container,
        stop: function(e, ui) {
         console.log($(this).attr("id"), $(this).getPosition()); //How do i store these positions into a variable and use it in other functions
        } 

});

Upvotes: 1

Related Questions