Shijin T R Shijin T R - 6 months ago 20
jQuery Question

Reverse order of two list at the same time with same order

I have two identical

<ul>
list ,I need to reverse the order of the two list using jQuery when i press a button.I have tried the bellow code and it is not working as expected.



function spin(){
spinList($('.list-view'));
}

var spinList = function($el){

var elementClone = $el.eq(0).clone();
var allLength = elementClone.find('li').length;
for(var i = 0;i<allLength;i++){
var element = elementClone.find('li').eq(allLength-i).clone();
$el.eq(0).find('li').eq(i).replaceWith(element);
$el.eq(1).find('li').eq(i).replaceWith(element);
}
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="spin()">Change order</button>

<ul class="list-view">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
<li>11</li>
<li>12</li>
</ul>

<ul class="list-view">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
<li>11</li>
<li>12</li>
</ul>




Answer

Use native JavaScript reverse() method

function spin() {
  spinList($('.list-view'));
}

var spinList = function($el) {
  $el.each(function() { // iterate over the list
    $(this).append( // appending to change the order
      $('li', this) // get the li element
      .get() // get them as array
      .reverse() // reverse the order
    )
  })
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="spin()">Click</button>

<ul class="list-view">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
  <li>9</li>
  <li>10</li>
  <li>11</li>
  <li>12</li>
</ul>

<ul class="list-view">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
  <li>9</li>
  <li>10</li>
  <li>11</li>
  <li>12</li>
</ul>

Comments