Nick Nick - 6 months ago 12
jQuery Question

jquery not changing css background-image property

I am trying to make a simple slideshow that changes the css background-image using JQuery.

Fiddle: http://jsbin.com/xinihokuso/edit?js,console



var images = [
"http://static1.squarespace.com/static/550b669de4b0d91b0f49935d/t/551b6575e4b0c2174c3a6f54/1427858806833/flowers.jpg?format=1500w",
"http://cimages.prvd.com/is/image/ProvideCommerce/PF_15_R105_MINIMAL_VA0211_W1_SQ?$PFCProductImage$",
"http://media02.hongkiat.com/ww-flower-wallpapers/purplecrocus.jpg",
"http://www.ninthstreetflowers.com/smp/Smp1/images/flower4.jpg",
"http://magic-spells-and-potions.com/images/flower-language-vertical.png",
];

var i = 0;

var div = $('.header_summer');

$(document).ready(function() {
console.log("loaded");

setTimeout(changeBack, 1000);
});

function changeBack() {
i = i = ++i % images.length;

if (i > images.length) {
i = 0;
}

console.log('url(' + images[i] + ') no-repeat 0 0;');

div.css('background', 'url(' + images[i] + ') no-repeat 0 0;');

setTimeout(changeBack, 5000);
}

<div class="header_summer"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>

<style type="text/css">

.header_summer {
background: url('http://static1.squarespace.com/static/550b669de4b0d91b0f49935d/t/551b6575e4b0c2174c3a6f54/1427858806833/flowers.jpg?format=1500w') no-repeat 0 0;
background-size: cover;
min-height: 920px; /* 800px; */
}

</style>





Everything looks right, the console is showing the correct CSS background-image value on each cycle, but all that is happening is the original image from the initial declared CSS is showing. Any ideas?

Please don't tell me to try to create unique CSS selectors for each image and simply change the style. That is not what I am trying to achieve here.

Answer

You need to remove the semi-colon(;) after declaring the pixels.

 div.css('background', 'url(' + images[i]  + ') no-repeat 0px 0px');

Working example : https://jsfiddle.net/DinoMyte/ez8cgsx7/8/

Comments