I have the following HTML structure:
<div class="change me">Item 1</div>
<div class="change me">Item 2</div>
<div class="change me">Item 3</div>
<div class="change me">Item 4</div>
<div class="change me">Item 5</div>
<div class="change me">Item 6</div>
And CSS:
body {
font-family: Helvetica, Arial, sans-serif;
font-size:20px;
}
div {
background-color: #fff;
display: block;
border-bottom: 1px solid #ccc;
background-image: url(http://cdn.sstatic.net/Img/mini-hero-bg.png?v=7f269bbbdb22);
}
.change {
background-image: none;
}
Now I would like to pic a random div with Javascript / jQuery and "remove" the class "change" so that the default background image of the specific div will be visible. My code looks like that atm:
var divs = $(".me").toArray();
var divlength = divs.length;
setInterval(function(){
var randomnum = Math.floor(Math.random()*divlength);
var randomdiv = divs[randomnum];
$(randomdiv).addTemporaryClass("change", 1000);
}, 1000);
$.fn.extend({
addTemporaryClass: function(className, duration) {
var elements = this;
setTimeout(function() {
elements.addClass(className);
}, duration);
return this.each(function() {
$(this).removeClass(className);
});
}
});
I need to improve this to achieve the following:
- I would like to have a smoother change from no-background-image to the visibility of the default background-image. Some fading effect or something like that. Already tried to add some transition to the div CSS but with no success.
- Sometimes there is no "change"-class removing and for some time no background-image of any div visible but I need at least one image being visible everytime
- I need to start the "remove"-class-thing immediately on page load so that there is already one background-image of a random div visible
Here is the current fiddle: http://jsfiddle.net/uRd6N/500/
Thx for your help, I am a noobie and not really familiar with JS / jQuery. If you know a better way to do this whole thing you could tell me too.
Regards