Reputation: 1045
I've been trying to use jQuery to have a button function reverse the order of a <ul>
.
For some reason the code completely messes up with the styling of the ul when clicked. It might be because of the lazy loader I'm using for the images (qazy.js), but I'm not entirely sure. It just seems to break the <ul>
.
You can see the live code here: http://designers.watch/tester.html
You'll see the undesirable effect when you click the 'Reverse Order' button.
The code I use the reverse the <ul>
is:
$(document).ready(function(){
$("#rev").click(function(){
var list = $("ul li").get().reverse();
$("ul").empty();
$.each(list, function(i){
$("ul").append("<li>"+list[i].innerHTML+"</li>");
});//each
});//function
});//ready
The two issues are:
Is there a way that I can fix these issues? Should I use a different lazy loader script?
Thanks in advance to anyone who helps out.
Upvotes: 0
Views: 2249
Reputation: 339786
You should never use HTML serialisation just to move elements around the page - as you'll find they lose things such as event handlers, styles, etc.
Just try this, instead:
$('#li-switch').on('click', function() {
// get reversed array of elements
var el = $('ul li').get().reverse();
// re-append them to their parent
$('ul').append(el);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="li-switch">Click to reverse the order</div>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
</ul>
As each node is appended it's automatically removed from its original position in the DOM, and put back in the right place unmodified.
Upvotes: 3
Reputation: 754
Your "Reverse Order" doesn't reverse your li
's, it is creating new ones and those new ones are different than those old ones - they are missing item
class plus you are loosing your schema attributes. This should do the trick in terms of improving what you already have:
$(document).ready(function(){
$("#rev").click(function(){
var list = $("ul li").get().reverse();
$("ul").empty();
$.each(list, function(i){
$("ul").append('<li class="item">'+list[i].innerHTML+'</li>');
});//each
});//function
});//ready
Check this question for more info about reordering list items: jQuery reversing the order of child elements
Lazy loader is a bigger problem, and I think it would need to be reinitialized after you do the reverese, since your list items and their children are new and don't have lazy loader events attached by the script. If you do reordering right this problem may disappear.
Upvotes: 0