Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQueryUI - Detect if element is beeing dragged

I want to get the position of an element when it is beeing dragged.

My code so far:

$(document).ready(function(){


    $("p").text($("div").position().left);
    $("p").text($("div").position().top);

    $("div").draggable();

})

This only gets the position when the page loads. I want to detect whenever the div is beeing dragged so I can write its position in the p tag.

like image 636
John Black Avatar asked Jan 12 '23 14:01

John Black


2 Answers

$('#dragThis').draggable(
    {
        drag: function(){
            var offset = $(this).offset();
            var xPos = offset.left;
            var yPos = offset.top;
            $('#posX').text('x: ' + xPos);
            $('#posY').text('y: ' + yPos);
        }
    });

JSFIDDLE

like image 188
Vaibs_Cool Avatar answered Jan 16 '23 00:01

Vaibs_Cool


You should have a look at the events section of the jQuery official documentation: http://jqueryui.com/draggable/#events

The drag event will be raised while being dragged and from there you can get the offset. For example:

$(this).offset().left;
$(this).offset().top;
like image 31
Mark Avatar answered Jan 16 '23 02:01

Mark