javascript - Change background-image using jQuery addClass -
is possible change css background using jquery addclass
? using following code stays on initial background image.
html
<div id="background"> </div>
jquery
$(document).ready(function() { (var x = 10; x > 0; x--) { $"#background").addclass(background2).delay(2000); $("#background").removeclass("background2"); $("#background").addclass("background3").delay(2000); $("#background").removeclass("background3").delay(2000); }; });;
css
#background { width: 100%; height: 100%; font-size: 1.5em; background-image: url(backgroundimage1.jpg); background-position: left; background-size: cover; background-repeat: no-repeat; background-attachment: scroll; } .background1 { background-image: url(backgroundimage1.jpg); } .background2 { background-image: url(backgroundimage2.jpg); } .background3 { background-image: url(backgroundimage3.jpg); }
you have 2 issues here. firstly you're adding classes , instantly removing them delay
not have effect on css()
method. achieve require use setinterval
instead. secondly, need increase specificity of backgroundx
classes override default styles on #background
element. try this:
var count = 0; var classes = [ 'background1', 'background2', 'background3' ]; function updatebackground() { $('#background').removeclass(classes.join(' ')).addclass(classes[count % classes.length]); count++; } setinterval(updatebackground, 2000);
#background.background1 { background-image: url(backgroundimage1.jpg); } #background.background2 { background-image: url(backgroundimage2.jpg); } #background.background3 { height: 20%; background-image: url(backgroundimage3.jpg); }
note example using background-color
principle same.
Comments
Post a Comment