(jQuery/JS) How to *set* a list item to be 1st in a UL or OL regardless of its original order?
I have this working code here:
function portfolio() {
$('#main-projects').children().toggle(function () {
$(this).css('cursor', 'pointer');
var projectname = $(this).attr('id');
//alert(projectname);
projectname = projectname.replace("li-", "main-");
$('.main-details').hide();
$('.main-stage').fadeOut(300);
$('#' + projectname).delay(300).fadeIn(900);
}, function () {
//Haven't written callback yet, no worries.
});
}
Works great already: when you click an LI (child of ul#main-projects
) it finds the name of the hidden slideshow div by replacing the name of the LI's id, replaces "li-(name of project)" with "main-(name of project)" then shows that div.
What I also want it to do (and can't seem to find the solution to) is 开发者_如何学运维take the LI that's been selected and move it to be the first in the list to curate in a way for the slideshow that's just been shown above it.
I know how to grab an item number with eq(index) but I haven't found anything that forces a reorder without dragging and dropping. Any ideas? Thanks in advance!
You can use insertBefore
to insert it before the first li
:
- http://api.jquery.com/insertBefore/
Also take a look at this question:
- Reordering of Divs
Well, assuming that your HTML is the same as you've described, then you can do it simply like this:
function portfolio() {
$('#main-projects li').toggle(function () {
var projectname = this.id.replace("li-", "main-");
$(this).css('cursor', 'pointer').prependTo('#main-projects');
$('.main-details').hide();
$('.main-stage').fadeOut(300);
$('#' + projectname).delay(300).fadeIn(900);
}, function () {
//Haven't written callback yet, no worries.
});
}
See a simple demo here: http://jsfiddle.net/yijiang/3zjSQ/
精彩评论