War Gravy War Gravy - 6 months ago 14
Javascript Question

JQuery, repositioning of children()

Using the JQuery function .children() I have selected 3 elements in the page. I want to perform a stable re-organizing on those elements so that they keep their order, but the desired element is elevated to the top. Here is an example:

I have elements:


  • A

  • B

  • C

  • D



I want C to be elevated to the top:


  • C

  • D

  • A

  • B



The code I have written for this assumes that all of the elements have unique ids and that you can provide that target id to perform the cycling or re-organizing of the elements:

function (parent, targetID) {
var feedEntries = $(parent).children(".items");
//reorder entries so that the first entry is the top entry
while (targetID != feedEntries.first().attr('id')) {
feedEntries.first().insertAfter(feedEntries.last());
}
}


The problem I have, is even though in theory this should work, it is crashing my page. Any help in solving this problem would be greatly appreciated.

Answer

You don't need a loop. .prepend() will put an element (or collection of elements) at the beginning of the parent. And you can use .slice() to get all the children starting from a particular index.

$("#button").click(function() {
  move('#list', 'c');
});

function move(parent, targetID) {
  var index = $("#" + targetID).index();
  var itemsToMove = $(parent).children().slice(index);
  $(parent).prepend(itemsToMove);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ol id='list'>
  <li id='a'>A</li>
  <li id='b'>B</li>
  <li id='c'>C</li>
  <li id='d'>D</li>
</ol>
<br>
<button id="button">Click to move</button>

Comments