I have the following html
<div id="to-sort">
<div class="block" data-id="1">aaaaa</div>
<div class="block" data-id="2">bbbbb</div>
<div class="block" data-id="3">ccccc</div>
<div class="block" data-id="4">ddddd</div>
<div class="block" data-id="5">eeeee</div>
<div class="block" data-id="6">fffff</div>
<div class="block" data-id="7">ggggg</div>
<div class="block" data-id="8">hhhhh</div>
<div class="block" data-id="9">iiiii</div>
</div>
I want to iterate through each .block and set its position to be absolute. I have the following
// Iterate through .blocks
$('.block').each(function(i,v){
var cssobj = { position: 'absolute',
top: $(this).position().top,
left: $(this).position().left };
console.log(cssobj);
//$(this).css(cssobj);
});
If the line
//$(this).css(cssobj);
is commented out – console.log() shows the correct positions. If I uncomment
$(this).css(cssobj);
then they are all set to the position of the first .block (x:0, y:0)
I am sure this to do with scope but I tried a closure and couldnt get it to work. How do i set each div to be an absolute position?
Thanks
jQuery
.position()gets the offset relative to the offset parent: http://api.jquery.com/position/jQuery
.offset()is what you are looking for.Also after the first one sets itself to
absolutethe next one moves up in its place.instead put it in two passes:
EDIT:-
as an alternative you can do it in reverse order and that will work also:
.reverse()is from JQuery .each() backwards