JQuery move div from position 1 to 2

I have several divs (having the same class names). I want to move the div (always the same div that has the unique identifier #pos1 ) to the div that was pressed. So, for this purpose, I use the following code to find position1 (the div I want to move) and pos2 (press div).

However, I do not know how I can move (animate, etc.) divs from one position to another. I will use 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); }); 
+6
source share
2 answers

First of all, make sure all your div .container position:absolute

Then you can use the following animate function for 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 }); }); 
+5
source

Both divs should have position :relative or maybe you can give your moving div a position: absolute for the top and left for the correct operation.

0
source

Source: https://habr.com/ru/post/922451/


All Articles