Steve
Steve

Reputation: 14912

How to re-order list items added by jQuery?

I found here by searching a good way to re-order list items.

$(".reOrder li").click(function() {
       var index = $(".reOrder li").index(this);
       if (index != 0) {
          // li item is not sitting in the first position
          $(".reOrder li:eq(" + (index - 1) + ")").before(this);
       }
       });

The problem is, I have LI items that I have added to the UL via jQuery's append method, and the clicks don't seem to be registered for those. Here's a simplified fiddle showing what I mean. Note how the original list items work fine, but if you add one, clicking on that has no effect.

I have even tried a simple click alert, so it's not getting the click event. How do I need to change my code to make this work?

Upvotes: 1

Views: 165

Answers (2)

OJay
OJay

Reputation: 4921

As per the jQuery documentation

> Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().

And also to respect the version of jQuery you are using on the fiddle (1.4.2 doesn't have .on() anyway). Best would be to use delegate

http://api.jquery.com/delegate/

as per the jQuery documentation

Deletegate() Description: Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.

or you could try instead of attaching to the click event of the li items, attach to the parent ul (which is always there) and then test the target (i.e. which li was clicked)

Upvotes: 1

adeneo
adeneo

Reputation: 318182

You're example code uses a class, and in the fiddle, it's an ID, but I guess you know that.

An event handler, like the one in your code, only works on elements that are present on the page at the time the events are bound. When adding elements, those would be dynamic, and you would you need a delegated event handler, where the event is bound to a non-dynamic parent, and checks for the second selector, in this case li :

$(".reOrder").on('click', 'li', function() {
     var index = $(".reOrder li").index(this);
     if (index != 0) {
        // li item is not sitting in the first position
        $(".reOrder li:eq(" + (index - 1) + ")").before(this);
     }
});

This won't work in jQuery 1.4, which is the version used in you fiddle, and you should upgrade to a newer version.

Upvotes: 2

Related Questions