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);
});
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.
Answer: Use the jQuery . appendTo() Method You can use the jQuery . appendTo() method to move an element into another element.
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.
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
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With