Is it possible to create a map to position elements?

3

I would like to know if it is possible to "pre-define" the position of an element when using append , for example:

<div id="mainDiv">
   <div class="child" data-position="2"></div>
   <div class="child" data-position="6"></div>
   <div class="child" data-position="7"></div>
   <div class="child" data-position="9"></div>
</div>

Now after a certain user action, let's say I need to use the following append :

$("#mainDiv").append('<div class="child" data-position="5"></div>');

By default the element will be added to the end of the current contents of div#mainDiv , however I would like to create a function that detects in which position such element should be added, which in the case would be between childs 2 and 6. >     

asked by anonymous 17.07.2018 / 18:05

1 answer

1

You can make a .each() by traversing the div s by checking the value in data-position of each element.

When you find a value greater than data-position of div to be inserted, the loop is canceled with return false; and the value of the element index coming from (e) is assigned to the idx variable.

No if after the loop you use .before() to insert div before element of class .child whose index is idx .

If the loop did not find an element with data-position greater, it means that all have% as data-position lower, so the value of idx will remain undefined and div will be inserted at the end with .append() :

function add(div){
   var pos = $(div).data('position'); // pega o valor do data-position
   var idx;
   
   $("#mainDiv .child").each(function(e){
      if($(this).data('position') > pos){
         idx = e; // idx pega o valor do índice encontrado
         return false; // aborta o loop
      }
   });
   
   if(idx >= 0){
      // O ":eq()" seleciona o elemento pelo índice (base zero)
      // No caso, a div com o valor data-position "6" é de índice 1
      $("#mainDiv .child:eq("+idx+")").before(div);
   }else{
     $("#mainDiv").append(div);
   }
}

// chama a função passando a div a ser inserida
add('<div class="child" data-position="5">5</div>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="mainDiv">
   <div class="child" data-position="2">2</div>
   <div class="child" data-position="6">6</div>
   <div class="child" data-position="7">7</div>
   <div class="child" data-position="9">9</div>
</div>

There are several ways to enter div . You can, for example, send to the function only the number of data-position and mount div within the function, among others.

    
17.07.2018 / 20:02