1

I have a function that creates an image object. I give the image a src and then I add a load function that adds the image to the DOM once loaded. It works except it's always adding 2 instances of the image to the page and I can't figure out why. Can someone tell me why this adds two images to my page?

var img = new Image();

$(img).load(function () {               
    $('#imageContainter').append(this);
    $(this).fadeIn();
})              
.error(function () {
    // notify the user that the image could not be loaded
})              
.attr('src', '' + _filename);   

"_filename" is the source path and "imageContainer" is the div that I load the image into.

Any help would be greatly appreciated.

1
  • 2
    Have you stepped through it in FireFox firebug or Chrome dev tools to see if it is getting called more than once? Commented May 30, 2013 at 16:44

1 Answer 1

4
$(new Image()).attr('src', '' + _filename).appendTo($('#imageContainter')).fadeIn();

Then if the 'error' part is important you can check the src or something.

I would also recommend using show() instead of fadeIn() if you're not supplying any fade time

Sign up to request clarification or add additional context in comments.

1 Comment

My guess would be that when you append the new DOM element the load method executes because the new element is loaded and when you supply a new source it executes again cause of the new image source.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.