tags:

views:

42

answers:

1

I use the load function to preload Images before applying a hover effect.

$("img").load(function(){ //image preloading

//some function & variable setting

    $listingItems.hover(
        function(){
            //effect
        },
        function(){
            //effect back
        }
    )

}) // load

the problem i have i that the effects only works if i reload the page. When i first come to the page, the images are loaded but there is no hover effect.

You can take a look at the source here: http://meodai.ch/rundum/shop.html

What have i done wrong? Can anyone help? Is there an other simple way to preload images before executing a function?

+2  A: 

The load event won't fire if the image comes from cache in some browsers, but there's a work-around for this by checking the .complete property and using .one() to make sure the load event handler only fires once, like this:

$("img").one('load', function(){
  //current code
}).each(function() {
  if(this.complete) $(this).load();
});

This loops though the images, if they're .complete (either loaded really fast or from cache) it triggers the load event handler, if it already ran (the really fast load case), not sweat, that's what the .one() is for.

Nick Craver
+1 Nice approach.
Ken Redler
wow thx did not know about one!
meo