How do I change the order of several tables based on mouse wheel scrolling in jQuery?
I have a div (#thelist) that contains a bunch of html tables. When the mousewheel is turned i want the first table to be removed and added to the bottom. (And the other way around if the wheel is turned in the other direction).
For some reason the code below works also from my understanding the list should juts get longer and longer. And since i don'开发者_运维问答t understand why it works this way i can't get it to work the other way around...
Any help ? Thank you!!!
$("#thelist").bind("mousewheel",function(ev, delta)
{
if (delta > 0)
{
var children = $("#thelist").children('table');
var tmpChild = children[0];
children.push(tmpChild);
}
if (delta < 0)
{
// How to do this, btw ?
}
$("#thelist").html(children);
}
I'm not sure how that would work either, but it could be cleaned up a little using the Javascript Array methods.
pop
- Remove the last item from the array and return it.
push
- Add the item to the end of the list.
shift
- Remove the first item from the array and return it.
unshift
- Add the item to the beginning of the list.
So your code would look like:
var children = $("#thelist").children('table');
if(delta > 0)
{
var tmpChild = children.shift();
children.push(tmpChild);
}
if(delta < 0)
{
var tmpChild = children.pop();
children.unshift(tmpChild);
}
The pop()
method should remove entries in your array one by one and add (see the EDIT) them to the top:splice()
if(delta < 0){
var child = children.pop();
children.unshift(child);
}
And you should put the children declaration and initialization statement before the if. And use a if/else if
$("#thelist").bind("mousewheel",function(ev, delta) {
var children = $("#thelist").children('table');
if (delta > 0){
var tmpChild = children[0];
children.push(tmpChild);
}else if (delta < 0) {
var tmpChild = children.pop();
children.unshift(tmpChild);
}
$("#thelist").html(children);
}
EDIT :
you should use the unshift()
instead of splice()
I'd go for something like this, to more clearly convey our intentions, "take the first child of #thelist and put it at the end of #thelist"
$("#thelist").bind("mousewheel",function(ev, delta)
{
var list = $("#thelist");
if (delta > 0)
{
list.children('table').first().appendTo(list);
}
if (delta < 0)
{
list.children('table').last().prependTo(list);
}
});
I suspect that this may also be a bit more efficient since it just rearranges the existing DOM elements rather than calling html()
to update the whole content of the list. The effect may be negligible, though.
精彩评论