Question

I have an image that is being resized programmatically, based on the current height/width of the container. My problem is that it shows the image at it's original size before it does the resizing.

See this JSFiddle

You'll notice how it flashes up a stretched image before it fits the image nicely in the middle.

I want to hide the image until that resizing has taken place, but I can't figure out how.

Any suggestions?

JSCode:

function LoadImg(img) {
    img.css('visibility','hidden');
    var src=img.attr('src');
    var imgh = img.parent().height();
    var imgw = img.parent().width();
    var pattern = /&?(w|h)=[^&]+/g;
    src = src.replace(pattern, '');
    img.attr('src', src + '&w=' + imgw + '&h=' + imgh);    
    img.css('visibility','');
}

Html:

<div class="window">
<img src="http://www.angclassiccarparts.co.uk/image_anysize.aspx?f=/images/ww/panel/service_kits.jpg&w=154&h=154&color=png" id="img" onload="LoadImg($(this));" />
</div>

I've tried hiding with visibility hidden until the function has run, but that doesn't wait for it to load...

Was it helpful?

Solution

You're changing the source of the image, which forces it to load a new image, then you instantly set the image to visible.

Ultimately you want to wait until the second image is loaded before showing it, which can be achieved using .load() like so:

img.on('load', function() {
    img.css('visibility','visible');
});

Here's an updated jsFiddle with the working code: http://jsfiddle.net/ev4YL/2/

I would, however, recommend a different approach. It doesn't make much sense to load an image, then when it's loaded load another image. Perhaps you should store the dimensions in html data attributes, then load the images dynamically on document.ready.

Something like this could work, if you set each image to have a data-src instead of src to begin with:

$('img').each(function() {
    var img = $(this);

    var src = img.attr('data-src');
    var imgh = img.parent().height();
    var imgw = img.parent().width();
    var pattern = /&?(w|h)=[^&]+/g;
    src = src.replace(pattern, '');
    img.attr('src', src + '&w=' + imgw + '&h=' + imgh);    

    img.on('load', function() {
        img.css('visibility','visible');
    });
});

And the demo here: http://jsfiddle.net/ev4YL/4/

OTHER TIPS

You can hide the image with display: none until the end of the function, then set the image to display: block (or whatever you need) at the very end. That way the rest of the function has already run, when it displays it will have already been resized.

See JSFiddle

But basically just: CSS:

img {
  display: none;
}

JavaScript:

function loadImg(img) {
  ----all of your function here----
  img.css('display', 'block');
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top