tags:

views:

257

answers:

2

I've got an issue where I was tying to center images using the jQuery Cycle plugin. I found this solution, but it wasn't working on single images (there isn't always > 2 images), so I wrote my own little bit of code, which seems to be working, except it sometimes doesn't subtract the height of the image from the height of the div, and so i end up with a margin of 310px.

var $image_cnt = $("#images > img").size();
    if($image_cnt < 2) {
        var $single_img = $("#images").children(':first-child');
        var h = $single_img.height();
        $single_img.css({
            marginTop: (620 - h) / 2,
        });
        $(".next").css("display","none");
        $(".prev").css("display","none");
    }

I haven't used jQuery much, and just wanted to know if I'd missed something simple, or had written something wrong, which is why the marginTop wasn't playing nice.

A: 

shouldn't this line:

var $image_cnt = $("#images > img").size();

be:

var $image_cnt = $("#images > img").length();

olso:

marginTop: (620 - h) / 2,

should be:

marginTop: (620 - h) / 2+'px',

One more thing you might want to check that each image has a hight set to it... and that the height is in pixels sometimes it could be in percentages, or other units.

hope it helps...

Val
+1  A: 

You should run this in

$(window).load(function {

So that the images are loaded, running it in $(document).ready(function { might execute before the images are ready, and if they're not, their heights will be 0 for the ones not .complete yet.

Nick Craver