jQuery delay function
I have some concept of how I might do this, but could really use an "optimizer" out there to tell me what to do, so it's done right.
This is my markup:
<span class="darkmark">
<em class="active rnr">RR</em>
<em class="apple">Apple Enthusiast</em>
<em class="glasses">Glasses Wearer</em>
<em class="html5">HTML5 User</em>
<em class="wine">Wine Drinker</em>
</span>
It's just a list of little icons that I want to cycle through in a header on a personal size. Cute right?
I would like every 5 seconds or so for the active class to move to the next sibling. Once the all the em's have been cycled through it returns to the first and the process go开发者_Python百科es on ad infinum.
Just don't know how I might do it. I don't want any user interaction to trigger it (no hover/click) just once the page loads they start cycling.
I realize that these should be in an ul li structure and plan to make that adjustment shortly.
There was a very similar question a day or two ago although I can't find it now. The solution I posted looked like:
var rotateSiblings = function() {
var cur = $('.active'); // find current "active", if any
var next = $(cur).next(); // find its next sibling
if (next.length == 0) { // if there wasn't one...
next = $('.darkmark').children().first(); // take the first one from the span
}
$(cur).removeClass('active'); // remove "active" from the current one
$(next).addClass('active'); // and add it to the next one
}
setInterval(rotateSiblings, 5000); // and do it all over every 5 seconds
EDIT - this code has been changed since first posting. Working demo at http://jsfiddle.net/raybellis/UHWfC/
Try something like this:
function change_active() {
var elements = $('.darkmark em');
var count = elements.length;
var active = $('.darkmark em.active');
var next = (active.index() + 1) % count;
active.removeClass('active');
$(elements.get(next)).addClass('active');
}
setInterval(change_active, 5000);
Look at it working here.
See example
var darkmarkRotate = function () {
var $this = $('.darkmark'),
$em = $this.find('em'),
$active = $this.find('em.active'),
$next = ($active.next('em').length) ? $active.next('em') : $em.first();
$active.fadeOut(500);
$next.delay(500).fadeIn(500);
setTimeout(function() {
$active.removeClass('active');
$next.addClass('active');
}, 1000);
setTimeout(darkmarkRotate, 5000);
};
darkmarkRotate();
精彩评论