King Kong
King Kong

Reputation: 2915

Dynamically adding divs through jquery

I am adding elements like div dynamically in the page using jquery.The div CSS is position : absolute .Now my problem is when i add more than 1 div element at the same time than it all overlaps each other. Is there any way so that without changing my element's position property these are not overlaps?

Upvotes: 1

Views: 208

Answers (3)

Hemen Ashodia
Hemen Ashodia

Reputation: 202

Check out masonry plugin. It is dynamic layout plugin that auto arranges the div elements as the new elements are added in document it prevents the overlaps of the elements. Check out this link.

Simply specify the container div let it with id container you need to call function

$(".container").masonry(); 

and then when you add more div inside container you just need to call the function

var $newElems = $( newElements );
$(".container").masonry( 'appended', $newElems );

Upvotes: 1

sabithpocker
sabithpocker

Reputation: 15558

When you add an element as positioned absolute and provide no valid top and left values the element will be positioned absolutes with both top and left as 0.

In your case all the elements you are adding should be taking position (0,0) so they are overlapping one above other.

One solution is to calculate the positions of each and layout them using adding corresponding top and left values to them along sith css({'position' : 'absolute'}) but that requires some math in most cases.

Dont worry, your browser already knows that math and you can use it in most cases, so add the divs without 'position' 'absolute'. Now browser layouts them well. After the browser has finished laying out them, take the DIVs and get their present position and use the position to layout them using absolute position.

for(var i=0; i < noOfDivs; i++){
    {
    $('#parentDiv').append('<div class="childDiv"/>');
    }
$('.childDiv').css({
    'position': 'absolute,
    'top' : $(this).position().top,
    'left' : $(this).position().left
    });

The code is not tested, if DIVs are positioned one by one it should again cause problems, you should either iterate them from last to first or save all positions and apply them later. If jQuery is updating all positions in a single DOM access this will work fine.

Upvotes: 0

jakee
jakee

Reputation: 18556

You define place of absolutely positioned objects with top, bottom, left, right css properties . So you have to alter these dynamically as well.

For example: The first element has top: 0, left:0 , the second top: 0, left: 50 and so forth...

Upvotes: 0

Related Questions