Is it possible to create a map to position elements?

Asked

Viewed 36 times

3

I wonder if it is possible to "pre-define" the position of an element when using a 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 content of div#mainDiv, however I would like to create a function that detects in which position such an element should be added that in case it would be between Childs 2 and 6.

1 answer

1


Can make a .each() traversing the divchecking the value in data-position of each element.

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

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

If the loop has not found an element with data-position larger, means that all have value in data-position smaller, hence the value of idx will continue indefinite and will 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>
<div id="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 various ways to insert the div. You can, for example, send to the function only the number of the data-position and mount the div within the function, among others.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.