I’m figuring out a possible solution for a dynamic crossfade of HTML elements. The core of my problem is a strange behaviour of the jQuery’s .position() and updating the css “position” property after retrieving the old position.
I’ve made a JSFiddle to illustrate my problem: http://jsfiddle.net/svenhanssen/DDYVs/
/*
This works. I'll get a position.top from 0 to 90
*/
$("p").each(function( p ) {
var position = $(this).position();
console.log(position.top);
});
/*
This doesn't work. I'll get a position.top of 0 for all elements. Why does the css set effects the position?
*/
$("p").each(function( p ) {
var position = $(this).position();
console.log(position.top);
$(this).css({
position: "absolute"
});
});
Somehow changing the css “position” property afterwards effects the old property. Does anyone know the reason why and a possible solution?
The moment you set a
<p>toposition: absoluteit is taken out of the document flow, and the next non-absolute<p>is moved upwards to take the freed space. Then you get to that just-repositioned<p>element, and sure enough itstopis now0(since there are no in-flow elements before it to push it down).Here’s a possible solution:
Note that now all
<p>elements are set toposition: absoluteonly after the loop has rolled.Updated fiddle