Prithviraj Mitra Prithviraj Mitra - 25 days ago 6
HTML Question

Sorting divs based on index using jquery

I am sorting 3 divs based on the position they are currently in. The sorting works fine but I am struggling to get the index value for each div.

The problem is,


  • when I click (down arrow) for div 2 it gives me the index value 0 where as it should give me 1.

  • If I click div 3 (up arrow) it gives
    me 0 instead of 2



Html code:

<div class="flow-container">
<div class="flow-block">
<div class="sort-arrows">
<span class="fa fa-arrow-up" id="sort-up"></span>
<span class="fa fa-arrow-down" id="sort-down"></span>
</div>
<div class="flow-content" data-key="2yqz1jpdxwy2g434zyo8r7k6vml9n50d">
<h3 class="bg-primary">Div 1</h3>
</div>
</div>
<div class="flow-block">
<div class="sort-arrows">
<span class="fa fa-arrow-up" id="sort-up"></span>
<span class="fa fa-arrow-down" id="sort-down"></span>
</div>
<div class="flow-content" data-key="q2qlvpm98n7d2kejzx3g5jy41r6wzx0p">
<h3 class="bg-primary">Div 2</h3>
</div>
</div>
<div class="flow-block">
<div class="sort-arrows">
<span class="fa fa-arrow-up" id="sort-up"></span>
<span class="fa fa-arrow-down" id="sort-down"></span>
</div>
<div class="flow-content" data-key="q2qlvpm98n7d2kejzx3g5jy41r6wzx0p">
<h3 class="bg-primary">Div 3</h3>
</div>
</div>
</div>


Demo -- https://jsfiddle.net/gvyoj63a/2/

Any help if highly appreciated.

Answer

Change

var pos = $(this).parent().index();

into

var pos = $(this).closest('.flow-block').index();

As .parent() selects the div which contains the up and down arrows.