user5735326
user5735326

Reputation:

Unable to alter the css 'background-image' with Jquery

I am trying to cycle through an array of pictures to make a photo-viewer on my webpage. The cycling method is working fine, but the transferring the message unto the css is not. I am wondering if there is any syntax issues within my javascript code or a concept that I am missing out on. I know that the cycling works because the alert I have is working.

var changeIt = ""
var backgroundPic = new Array(4);

backgroundPic[0] = '("images/displayPic1.jpg")';
backgroundPic[1] = '("images/displayPic2.jpg")';
backgroundPic[2] = '("images/displayPic3.jpg")';
backgroundPic[3] = '("images/displayPic4.jpg")';
backgroundPic[4] = '("images/displayPic5.jpg")';

var picCounter = 0;
var numberOfPics = 5;
var picTimer;

function setPic(){
    alert("hi I want this pic: " + backgroundPic[picCounter]);
    $('slider').css('background-image', url + "backgroundPic[picCounter]");

    picCounter += 1;
        if(picCounter >= numberOfPics){
        picCounter = 0;
    }

}

$(document).ready(function(){

    $('.slider').css('background-image', backgroundPic[picCounter]);

    picTimer = setInterval(setPic, 2000);

});

Upvotes: 0

Views: 44

Answers (5)

Rory McCrossan
Rory McCrossan

Reputation: 337560

The issue is due to the incorrect syntax you're using when concatenating the CSS property value. Try this:

var backgroundPic = [ 'images/displayPic1.jpg', 'images/displayPic2.jpg', 'images/displayPic3.jpg', 'images/displayPic4.jpg', 'images/displayPic5.jpg' ];    
var picCounter = 0;
var picTimer;

function setPic() { 
    // note the . in the jquery object below to indicate a class selector
    $('.slider').css('background-image', 'url("' + backgroundPic[picCounter % backgroundPic.length] + '")');
    picCounter++;
}

$(document).ready(function() {
    picTimer = setInterval(setPic, 2000);
    setPic();
});

Upvotes: 1

Aparna
Aparna

Reputation: 255

You'll need to include double quotes (") before and after the imageUrl like this:

$('slider').css('background-image', 'url("' + backgroundPic[picCounter] + '")');

This way, if the image has spaces it will still be set as a property.

Upvotes: 0

iomv
iomv

Reputation: 2697

On your setPic function, this line

$('slider').css('background-image', url + "backgroundPic[picCounter]");

isn't missing a dot on $('.slider')?

Upvotes: 0

Marcos Lima
Marcos Lima

Reputation: 771

You inverted the positioning of the quotemarks on the second line of setPic.

Try: $('slider').css('background-image', 'url' + backgroundPic[picCounter]);

Upvotes: 0

Mahesh Chavda
Mahesh Chavda

Reputation: 593

You have to set background image like this:

$('.slider').css('background-image', "url('" + backgroundPic[picCounter] + "')");

Upvotes: 0

Related Questions