Newbie here! My problem is as follows: I have a dynamically populating ul where each li item contains 5 absolutely positioned inner divs. Like this:
<ul id="slider">
<li class="slide">
<div class="pic1"></div>
<div class="pic2"></div>
<div class="pic3"></div>
<div class="pic4"></div>
<div class="pic5"></div>
</li>
<li class="slide">
<div class="pic1"></div>
<div class="pic2"></div>
<div class="pic3"></div>
<div class="pic4"></div>
<div class="pic5"></div>
</li>
//more li items...
</ul>
Each one of these absolutely positioned divs uses a sibling’s height to calculate its final position with jQuery. The horizontal (left, right) properties are applied directly through css. I tried using the each method for each pic class to set the css, like these examples:
var pic2 = new Array();
$('.slide .pic2').each(function(i) {
pic2.push($(this).siblings('.pic1').find('img').height();
$(this).css({ top : pic2[i] + 10 });
});
var pic4 = new Array();
$('.slide .pic4').each(function(i) {
pic4.push($(this).siblings('.pic3').find('img').height();
$(this).css({ top : pic4[i] + 10 });
});
But I think there must be a simpler, more compact way to do this, as this seems like too complicated and also it breaks in IE7 and IE8, I noticed. Maybe a for loop for example that will create a multidimensional array and will apply the css to each item according to certain if statements, or perhaps using the .position method? Any ideas? Thank you!
—- Edit to add Answer for Future newbies like myself:
Using Shasteriskt’s answer I was able to streamline my ugly each functions and also add certain parameters according to class, like this:
$('.slider li').children('div').each(function(i,picItem){
if ( $(this).hasClass('pic2') ) {
var top = $(picItem).prev().find('img').height();
$(picItem).css({top: top + 100});
}
if ( $(this).hasClass('pic5') ) {
var top = $(picItem).prev().find('img').height();
$(picItem).css({top: top + 60});
}
else {
var top = $(picItem).prev().find('img').height();
$(picItem).css({top: top + 10});
}
});
Thank you, Shasteriskt! Lots of chocolate cookies for you! 🙂
Any reason why you need to push each value into the array? Unless you need to use it after, I don’t think you really need it.
You can streamline this as follows: