0

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.

2
  • You are using the same id's for each of the sort-up / sort-down spans. Each Id needs to be unique. Commented Nov 13, 2016 at 0:29
  • Yes right. I will give unique ids. Thanks. Commented Nov 13, 2016 at 0:59

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant. Worked great. Thank you so much.
1

Your selector for getting the index is selecting the div group that's wrapping the arrows, not the item div.

try something like:

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

1 Comment

Thanks Andy. Understood now. Thanks once again.
0

Cleaner code

$("body").on('click tap', '.fa-arrow-down, .fa-arrow-up', function(e) {
  e.preventDefault();
  var elem = $(this).closest(".flow-block");
  var pos = elem.index();
  alert(pos);
  if($(this).hasClass('fa-arrow-down')) {
    elem.next().after(elem);
  } else {
    elem.prev().before(elem);
  }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.