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, 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 = [
// preload images
$.each(imgs,function(i,e){var i=new Image();i.src=e;});

// populate the image with first entry

var opacity = 0.1; // change this for minimum opacity
function changeBg() {




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;
        var val = "url('" + imgs[i++] + "')";

Here is the updated demo.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.