So, I read a bunch of other solutions on the same issue, but none of them seem to work.
I have a bunch of images, most of which are hidden when the page loads. Only the first image is visible. What I need to do is give them a negative top edge to center the image vertically. The only problem is that the code that I have now is very inconsistent and only works from time to time. I'm not really sure if this is my code, or if the image is cached or something like that.
This is what I have:
$('#frontpage-sidebar-slideshow img').each(function(i, v) { // I read that preloading the images would solve the problem, but this doesn't do anything //var src = $(this).attr('src'); //$('<img/>')[0].src = src; // First make parent .slide visible to be able to get the image dimentions (not possible if image is invisible) var showAfter = false; if(!$(this).parent('.slide').is(':visible')) { showAfter = true; $(this).parent('.slide').css({ // .show() might also work display: 'block', visibility: 'visible', opacity: 1 }); } // Get dimentions var wrapHeight = parseInt($('#frontpage-sidebar-slideshow').height(), 10) + 20; var imgHeight = $(this).height(); var offset = Math.ceil((wrapHeight - imgHeight) / 2); // Set offset if needed if(imgHeight > wrapHeight) { $(this).css('margin-top', offset); } // Show image again if needed if(showAfter) { $(this).parent('.slide').show(); } });
I use SlidesJS to create image slide shows. HTML formatting is as follows:
<div class="slide"> <a href="url goes here"> <img width="200" src="image src goes here" alt="" style=""> <div class="overlay"> <p class="title"> Some title </p> <p> Some content </p> <p> More content </p> </div> </a> </div> <div class="slide" style="display: none;"> <a href="url goes here"> <img width="200" src="image src goes here" alt="" style=""> <div class="overlay"> <p class="title"> Some title </p> <p> Some content </p> <p> More content </p> </div> </a> </div>
There are two problems:
1) The first image gets very inconsistent results. Sometimes I get the wrapper value (height .slide ), and sometimes I get the actual height value. I have no idea what that means.
2) No matter what I do, I get only the height value for the first image. The rest of the images just return 0 . Yup, they donβt even return the wrapper height ( .slide height), which is strange.
Any ideas?
Update I just realized that snides and SlidesJS and my script work on pageload, they can collide (I'm trying to display images, get their sizes, and then hide them, and SlidesJS wants to hide all of them except the first one), so I tried to wrap the whole script is higher in setTimeout(code, 300) and now it at least seems to give me consistent results for the first image, but the rest of the images still return 0.