Reputation: 6666
I have a really simple jQuery problem (I guess). But im totally new to jQuery and having a hard time to solve this.
i have a list
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
Every 5 secs i would like to rotate this. So every item moves up (the first one gets to the last place).
Which is the easiest way to solve this?
Upvotes: 0
Views: 358
Reputation: 141827
The easiest way is to get a nice animation is with the Quicksand plugin for jQuery:
It would look like this:
var lis = $('ul.list').children('li').get();
$('ul.list').quicksand($('<ul>').append(lis).children());
setInterval(function(){
lis.push(lis.shift());
$('ul.list').quicksand($('<ul>').append(lis).children());
}, 5000);
You will also need to add a "data-id" attribute to your li
's so Quicksand can animate them nicely:
<ul class="list">
<li data-id="item1">Item 1</li>
<li data-id="item2">Item 2</li>
<li data-id="item3">Item 3</li>
<li data-id="item4">Item 4</li>
</ul>
Upvotes: 1
Reputation: 1251
Using jQuery.animate:
function menu() {
$menu = $('#menu');
$first = $menu.find("li").first();
$first.animate({marginTop:-1 * $first.height()}, 1000, 'linear', function () {
$menu.append($first);
$first.attr('style', '');
});
}
setInterval("menu()", 5000);
Upvotes: 0
Reputation: 338228
setInterval(function () {
$("ul").append( $("ul li:first") );
}, 5000);
You should give the <ul>
an ID to make it unambiguous. See it in action.
Upvotes: 4
Reputation: 707396
Give the ul
an id like this:
<ul id="myList">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
Then, you can use this jQuery with setTimeout()
:
var list$ = $("#myList");
function rotateList() {
list$.find("li:first").appendTo(list$);
setTimeout(rotateList, 5000);
}
rotateList();
Demonstration here: http://jsfiddle.net/jfriend00/KVzXa/ (running every 1 second for purposes of the demo).
Or, it could also be done with setInterval()
like this:
var list$ = $("#myList");
setInterval(function() {
list$.find("li:first").appendTo(list$);
}, 5000);
I chose to save a little CPU in both implementations by caching $("#myList") rather than rerunning it on every rotation.
Upvotes: 1
Reputation: 19022
function rotate(){
$('li').first().detach().appendTo($('ul'));
setTimeout(rotate, 1000);
}
rotate();
Demo: http://jsfiddle.net/yXRpJ/
Upvotes: 0