How to change the css attribute of #header using jQuery and an array of images?

I am trying to edit a script that changes the images of a div as shown below, to change the background-image property of #header.

As you can see in my fiddle here, http://jsfiddle.net/HsKpq/460/ I am trying to show the images into the $('#header').css('background-image',..................).fadeTo('slow',1);

How can I do this? I guess I have to change some other parts too..

var img = 0;
var imgs = [
    'http://www.istockphoto.com/file_thumbview_approve/9958532/2/istockphoto_9958532-sun-and-clouds.jpg',
    'http://www.istockphoto.com/file_thumbview_approve/4629609/2/istockphoto_4629609-green-field.jpg',
    'http://www.istockphoto.com/file_thumbview_approve/9712604/2/istockphoto_9712604-spring-sunset.jpg'
];
// preload images
$.each(imgs,function(i,e){var i=new Image();i.src=e;});

// populate the image with first entry
$('img').attr('src',imgs[0]);


var opacity = 0.1; // change this for minimum opacity
function changeBg() {
    $('img').fadeTo('slow',opacity,function(){
        $('#header').css('background-image',..................).fadeTo('slow',1);
    });
}



setInterval(changeBg,5000);

Answers:

Answer

You need a couple of fixes:

  • Use a simple increment to keep track of the current image.
  • typo: "images" -> "imgs"
  • $("img") doesn't select anything, so the JQuery fadeto "complete" callback is never fired (I assume you meant to fade the div itself)
  • you need "url('http://...')" for the "background-image" CSS property

function changeBg() {
    if (i >= imgs.length) i=0;
    $('#header').fadeTo('slow',opacity,function(){
        var val = "url('" + imgs[i++] + "')";
        console.log(val);
        $('#header').css('background-image',val).fadeTo('slow',1);
    });
}

Here is the updated demo.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.