-1

I have a list, which is sortable using jQuery UI sortable:

<ol id="sortable" class="ui-sortable">
  <li style="margin-left:10px; width:100%;" class="block_anchor" data-id="498">Step 1</li>
  <li style="margin-left:10px; width:100%;" class="block_anchor" data-id="499">Step 2</li>
  <li style="margin-left:10px; width:100%;" class="block_anchor" data-id="500">Step 3</li>
  <li style="margin-left:10px; width:100%;" class="block_anchor" data-id="501">Step 4</li>
</ol>

When the page loads, there aren't any <li> items: I add them with jQuery by clicking on a button.

Right now, I can sort the list, but I'd also like to be able to change the position when I click on a <li></li> element. I keep track of the elements position with their css attribute order(the <ol> elements is a flexbox so every item inside has an order). What I'm trying to do is to increment the order of an element of 1 when I click on it.

Here is what I did so far:

$('#sortable li').map(function(i, item){
  var id = $(item).data('id');
  $('li[data-id='+ id +']').on( "click", function() {
    console.log("Clicked");
    $('li[data-id='+ id +']').css('order', i + 1);
  })
});

But even the console.log isn't appearing. Is it due to the fact that the <li> items are added onClick of a button so they aren't here on page load when the function is executed ?

How should I proceed to go further ?

EDIT: this is not a duplicate, the topic mentionned was about reordering everything, which is not why I'm trying to do here

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
Graham Slick
  • 6,692
  • 9
  • 51
  • 87
  • Possible duplicate of [jquery sort list based on data attribute value](http://stackoverflow.com/questions/21600802/jquery-sort-list-based-on-data-attribute-value) – Rahul Singh Mar 18 '16 at 09:52

1 Answers1

1

Check what the .map callback does, the first argument returns the item and the second one will give you the index.

I think that is what you're doing wrong there because when you increment the i var, you are really adding 1 to the element you get from the list.

Forget what I said before, this uses the jQuery map so It works like you wrote before.

This may help you in what you're trying to achieve:

$('#sortable li').map(function(i, item){
    var id = $(item).attr("data-id");

    // This will set the order of each item based on the position in the array.
    $('li[data-id='+ id +']').css('order', i)

    $('li[data-id='+ id +']').on( "click", function() {
      console.log("Clicked");

      var clickedItem = $('li[data-id='+ id +']'),
          currentOrder = Number(clickedItem.css('order'));

      clickedItem.css('order', currentOrder + 1);
    })
});

https://jsfiddle.net/jLqouzv4/

Horus Lugo
  • 61
  • 1
  • 5
  • Thanks for your answer. However, even if I'm wrong about the i var, the console.log should appear on click ... I'm trying to figure out why the console.log isn't there first, before being able to fix the incrementation – Graham Slick Mar 18 '16 at 10:04