Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery move div from position 1 to 2

I have multiple divs (haveing same class names). I want to move the div (always same div, which has unique ID #pos1) to the div which has been clicked. So, for that purpose, I am using following code to find the position1 (of the div which I want to move) and pos2 (the div which is clicked).

However, I don't know know how can I move (animate etc) the div from one position to another. I will appriciate any help.

jQuery(".container").click(function() {

    var pos1 = jQuery("#pos1").position();
    alert(pos1.top + ', ' + pos1.left);

    var pos2 = jQuery(this).position();
    alert(pos2.top + ', ' + pos2.left);

});
like image 266
user1355300 Avatar asked Aug 09 '12 09:08

user1355300


People also ask

How do I move a DIV from one place to another in jQuery?

All you have to do is select the element(s) you want to move, then call an “adding” method such as append() , appendTo() or prepend() to add the selected elements to another parent element. jQuery automatically realises that the element(s) to add already exist in the page, and it moves the element(s) to the new parent.

How do I move a div to another div?

Answer: Use the jQuery . appendTo() Method You can use the jQuery . appendTo() method to move an element into another element.

How to get position of div in jQuery?

jQuery position() MethodThe position() method returns the position (relative to its parent element) of the first matched element. This method returns an object with 2 properties; the top and left positions in pixels.


1 Answers

First of all make sure that all your .container divs are position:absolute

Then you can use the following animate function of jQuery:

$('.container').click(function(){
    var pos1 = $('#pos1').position();

    $(this).animate({ 'top': pos1.top + 'px', 'left': pos1.left + 'px'}, 200, function(){
        //end of animation.. if you want to add some code here
    });
});
like image 132
udidu Avatar answered Sep 28 '22 06:09

udidu