Question

I want to preload rollover images in jQuery but the list of images is inside list of like this:

<li><a href="/images/1.jpg"></a></li>
<li><a href="/images/2.jpg"></a></li>
<li><a href="/images/3.jpg"></a></li>

==========

function preload(arrayOfImages) {
    $(arrayOfImages).each(function(){
        $('<img/>')[0].src = this;
    });
}

var imagelist = $('li a').attr("href");
preload(imagelist);

I changed the last line so it just grab the href from my list. Original script was from: Preloading images with jQuery

Is this correct?

Was it helpful?

Solution

You can use $.map to convert the nodeList into an array of hrefs:

var imageList = $('li a').map(function() {
    return this.href;
});

preload(imageList);

Or skip the preload function and do a simple loop instead:

$('li a').each(function() {
    (new Image).src = this.href;
});

If you want to use it as a plugin try:

$.fn.preload = function() {
    return this.each(function() {
        (new Image).src = this.href;
    });
};

$('li a').preload();

OTHER TIPS

You can do this:

var imagelist = $('li a').each(function() {
    preload($(this).attr("href"));
});

Or you can do this:

$.fn.preload = function() {
    this.each(function(){
        //alert("preloading " + $(this).attr("href"));
        $('<img/>')[0].src = $(this).attr("href");
    });
}
$('li a').preload();

jsFiddle

You can populate your imagelist like this to make it an array:

var imagelist = [];
$('li a').each(function(){
  imagelist.push($(this).attr('href'));
})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top