0

I am looking to run a function based on when the background image of the div loads. What am I missing?

JQUERY

$(function () { 
    $('.productnew .imgframe').each(function () { 
        $(this).load(function () { 
            $(this).attr("style", $(this).attr("style").replace("background:", ""));
            $(this).attr('style', 'background:url(images/new.png), ' + $(this).attr('style')); 
        }); 
    }); 
});

HTML

<div class="poster productnew"><div class="imgframe" style="background:url(images/posters/bicycle.jpg);"></div>
  • More details please - what is happening when you run your code? – Zachary Kniebel Apr 12 '13 at 18:14
  • Possible duplicate: http://stackoverflow.com/questions/5057990/how-can-i-check-if-a-background-image-is-loaded – Dom Apr 12 '13 at 18:15
  • 1
    Please show us your HTML. Only some types of elements have onload events. We need to see what types of elements you're using. For example, I'm not aware of any way to get an onload event for a background image. You could load the image manually into your own image object with JS and then once that had loaded set it as a background image. – jfriend00 Apr 12 '13 at 18:15

1 Answers1

1

A div element (your <div class="imgframe"> element) does not have an onload event so that's why you aren't getting the event.

Some of the elements which have onload events are <image>, <body>, <iframe>.

If you need to know when that particular image is loaded to trigger other code, you can load the image manually using javascript into an image object and then when that onload event fires, you will know that the image is loaded and you can trigger other events (set it as the background URL or whatever else you wanted to do).

jfriend00
  • 683,504
  • 96
  • 985
  • 979