Reputation: 489
I have a code to loop images but based on an Img source, but how to improve it to make it work for the "background-image" property of a div?
HTML
<div id="section2"></div>
CSS
#section2 {
background-image: 'url(..images/banner1.jpg');
}
JAVASCRIPT
<script type = "text/javascript">
(function() {
var i = 1;
var pics = [ "images/banner1.jpg", "images/banner2.jpg", "images/banner3.jpg" ];
var el = document.getElementById('section2');
function toggle() {
el.src = pics[i];
i = (i + 1) % pics.length;
}
setInterval(toggle, 3000);
})();
</script>
Thanks in Advance :)
Upvotes: 0
Views: 353
Reputation: 16181
One way would be to use CSS classes instead of sources.
JS:
<script type = "text/javascript">
(function() {
var i = 1;
var classes = [ "bgd-1", "bgd-2", "bgd-3" ]; // adjusted
var el = document.getElementById('section2');
function toggle() {
el.className = classes[i]; // adjusted
i = (i + 1) % classes.length; // adjusted
}
setInterval(toggle, 3000);
})();
</script>
CSS:
#section2.bgd-1 {
background-image: url('..images/banner1.jpg');
}
#section2.bgd-2 {
background-image: url('..images/banner2.jpg');
}
#section2.bgd-3 {
background-image: url('..images/banner3.jpg');
}
Note:
Use el.className += ' ' + classes[i];
to append a class name instead of replacing all element classes.
Upvotes: 1