views:

604

answers:

3
$('.ro').hover(
    function(){
        t = $(this);
        t.attr('src',t.attr('src').replace(/([^.]*)\.(.*)/, "$1_o.$2"));
    },
    function(){ 
        t = $(this);
        t.attr('src',t.attr('src').replace('_o',''));
    }
 );

I use this code so that (for examle) test.gif with the class 'ro' would change to test_o.gif on rollover, the problem is when the images aren't in the cache there is lag on rollover and rolloff.

Basically if I clear my cache and visit the test page, everytime I rollover and rolloff the image it is loading the file each time, so you could sit there for hours and it would still be loading the rollover images each time. However, when I refresh the page and the images are now in the cache it works instantly, which is what I need to achieve.

I've tried using this

http://flesler.blogspot.com/2008/01/jquerypreload.html

plugin to preload the images with this

$.preload('.ro');

code, but it seems to have no effect.

Any ideas?

+2  A: 

Just create a dummy image(s) on doc ready, no need for a plugin.

$(function(){
   $('<img />').attr('src',url);
});
redsquare
+1  A: 

See this:

http://stackoverflow.com/questions/476679/preloading-images-with-jquery

karim79
neither of the answers so far solve my problem :(
zuk1
A: 

Combine yours with the one on http://stackoverflow.com/questions/476679/preloading-images-with-jquery and you get a short script that will preload the images then hover them for anything with the nominated selector. eg

    //preload images
    $('.ro').each(function(){
        $('<img/>').appendTo('body')
            .css({ display: "none" })
            .attr('src',$(this).attr('src').replace(/([^.]*)\.(.*)/, "$1_on.$2"));
    });
    //hover them
    $('.ro').hover(
        function(){
            t = $(this);
            t.attr('src',t.attr('src').replace(/([^.]*)\.(.*)/, "$1_on.$2"));
        },
        function(){ 
            t = $(this);
            t.attr('src',t.attr('src').replace('_on',''));
        }
     );

This approach is appending them to the body tag to deal with the issue of IE discarding images that aren't added to the DOM (as mentioned in the other post relating to this) but you could stick them anywhere that makes sense for you.

I like the approach in this post as you don't have to declare an array of images ahead of time, simply adopt a naming convention for rollovers and a class name and you're sorted.

benz001