Question

First post. I've searched high and low for similar questions and have come up empty handed, so here goes.

I am currently using small bit of jQuery to proportionally scale a collection of images for display in an image carousel (thanks to SO users for much of this code). The carousel is powered by the jCarousel Lite plugin (here). I have 4 different image sets, which are selected using a navigation menu. When a new image set is selected, the following jQuery resizing code executes on each image in the set, and then the image carousel is initialized using the freshly resized images within the #slider div.

The problem: this code only works sometimes, seemingly randomly. When the slider initializes, if the images are not scaled successfully, all widths are increased to maximum width, thus cropping the bottom of the image. This problem is especially apparent for portrait-oriented images, as the slider is shaped for landscape-oriented images (900px x 600px). I cannot pinpoint what causes the code to work successfully or not, regardless of order or clicks, window size, or browser.

Any ideas why this code would randomly execute successfully?

//The following scales images proportionally to fit within the #slider div
$('#slider ul li img').each(function() {
    var maxWidth = $('#slider').outerWidth(false); // Max width for the image
    var maxHeight = $('#slider').outerHeight(false);    // Max height for the image
    var ratio = 0;  // Used for aspect ratio
    var width = $(this).width();    // Current image width
    var height = $(this).height();  // Current image height

// Check if the current width is larger than the max
if(width > maxWidth){
    ratio = maxWidth / width;   // Ratio for scaling image
    $(this).css("width", maxWidth); // Set new width
    $(this).css("height", height * ratio);  // Scale height based on ratio
    height = height * ratio;    // Reset height to match scaled image
}

var width = $(this).width();    // Current image width
var height = $(this).height();  // Current image height

// Check if current height is larger than max
if(height > maxHeight){
    ratio = maxHeight / height; // Ratio for scaling image
    $(this).css("height", maxHeight);   // Set new height
    $(this).css("width", width * ratio);    // Scale width based on ratio
    width = width * ratio;    // Reset width to match scaled image
}
});
initialize(); //initializes the jCarousel Lite carousel
Was it helpful?

Solution

Have you tried running it on window load jQuery(window).load(function() {

This will help ensure that all of the images are available before checking their dimensions

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top