What I'm looking for is a way to make my HTML header tag change background images every few seconds. Any solutions are welcome, as long as it is not to complex.
I have this code right now as well as linking to JQuery:
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
$(function() {
var header = $(‘.mainHeader’);
var backgrounds = new Array(
‘url(img/rainbow.jpg)’,
‘url(img/chickens_on_grass.jpg)’
‘url(img/cattle_on_pasture.jpg)’
‘url(img/csa_bundle.jpg)’
);
var current = 0;
function nextBackground() {
header.css(‘background’,backgrounds[current = ++current % backgrounds.length]);
setTimeout(nextBackground, 10000);
}
setTimeout(nextBackground, 10000);
header.css(‘background’, backgrounds[0]);
});
My HTML header:
<header class="mainHeader"></header>
And CSS:
.mainHeader {
background: no-repeat center bottom scroll;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
min-height: 150px;
padding-top: 2%;
font-size: 100%;
}
Right now I have now background image at all.
Made a few amendments to your code
DEMO: http://jsfiddle.net/p77KW/
var header = $('body');
var backgrounds = new Array(
'url(http://placekitten.com/100)'
, 'url(http://placekitten.com/200)'
, 'url(http://placekitten.com/300)'
, 'url(http://placekitten.com/400)'
);
var current = 0;
function nextBackground() {
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:
current
then take modulus (I know this is basically what you did but how much easier is that to debug ;)
)background-image
directlysetInterval()
instead of a double call to setTimeout
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With