Dynamically Changing Css Background Image
Solution 1:
Made a few amendments to your code
DEMO: http://jsfiddle.net/p77KW/
var header = $('body');
var backgrounds = newArray(
'url(http://placekitten.com/100)'
, 'url(http://placekitten.com/200)'
, 'url(http://placekitten.com/300)'
, 'url(http://placekitten.com/400)'
);
var current = 0;
functionnextBackground() {
current++;
current = current % backgrounds.length;
header.css('background-image', backgrounds[current]);
}
setInterval(nextBackground, 1000);
header.css('background-image', backgrounds[0]);
Biggest changes (as noted in others comments) is that you have to use apostrophe**'**s, not those funky open and close single-quotes and that your array wasn't correct.
With these corrections out of the way I simplified a few things:
- Increment
current
then take modulus (I know this is basically what you did but how much easier is that to debug;)
) - Target
background-image
directly - Used
setInterval()
instead of a double call tosetTimeout
Solution 2:
You could acheive this same technique with HTML/CSS Only by 1. placing images within an "img" tag in your HTML surrounded by a "div wrapper" and setting it to position:relative and div wrapper img's to position:absolute. For full-width/full-height you can use percentages or potentially "background-size:cover" (haven't checked) and then call a CSS animation to change the images dynamically.
Or 2. you can add multiple images to a background in your CSS separated by commas, apply background-size:cover and again use CSS animations to change the background.
Here's an example and also Mozilla CSS3 Animation Documentation
Solution 3:
<html><head><scriptsrc="http://code.jquery.com/jquery-1.11.0.min.js"></script><script>
$(document).ready(function(){
var header = $('body');
var backgrounds = newArray(
'url(http://placekitten.com/100)'
, 'url(http://placekitten.com/200)'
, 'url(http://placekitten.com/300)'
, 'url(http://placekitten.com/400)'
);
var current = 0;
functionnextBackground() {
current++;
current = current % backgrounds.length;
header.css('background-image', backgrounds[current]);
}
setInterval(nextBackground, 1000);
header.css('background-image', backgrounds[0]);
});
</script></head><body><header></header></body></html>
Solution 4:
You can't delimit JavaScript strings with ‘
characters. You must use "
or '
.
Solution 5:
It must be late but may help to another one. For this goal in some situations I prefer to use a jquery plugin named tcycle which have only a few lines of code and supports just fade transition, but it works smoothly even with large images.
Setting up a slideshow with tcycle is easy and even could be done with declarative markup such as
<div class="tcycle">
<imgsrc="p1.jpg"><imgsrc="p2.jpg"></div>
The trick could be donde using css z-index:-1 for container div and setting width and height to 100%
Homepage for downloading and check for other examples is Malsup jQuery plugins
Post a Comment for "Dynamically Changing Css Background Image"