How to leave items in a highlighted list, changing the position regardless of where it appears

0

I'm building an application with no database and with json, I'm using a <ul><li></li></ul> list to display the items, What I need is to make some items stand out. Ex.

Here's a regular list, how I'm displaying

<li>Item 1</li> 
<li>Item 2</li> 
<li>Item 3</li> 
<li>Item 4 (destaque)</li> 
<li>Item 5</li> 
<li>Item 6</li> 
<li>Item 7(destaque)</li> 
<li>Item 8</li>

Here the list I want to show already changed

<li>Item 4 (destaque)</li> 
<li>Item 7(destaque)</li> 
<li>Item 1</li> 
<li>Item 2</li> 
<li>Item 3</li> 
<li>Item 5</li> 
<li>Item 6</li> 
<li>Item 8</li>

I have already researched several filters in Jquery, but none of them meet my needs.

    
asked by anonymous 26.01.2018 / 02:14

1 answer

0

If you want to show the ones that have highlights at the top then you need to sort them. Assuming only part of the information that is in the html, you can do the ordering with sort based on the result that comes from a JQuery selector.

This ordering would be according to the criteria you want, by first ordering by highlight and then by name. After that, simply move the elements in the html to the ordered position.

Example:

$(".lista li").on("click", function(){
  $(this).toggleClass("destaque"); //alternar destaque no clique
  atualizaLista();
});

function atualizaLista(){
  let listaOrdenada = $(".lista li").sort((a,b) => {
    let a_destaque = a.classList.contains("destaque");
    let b_destaque = b.classList.contains("destaque");
    
    if (a_destaque == b_destaque) //se ambos com o mesmo destaque
      return a.textContent.localeCompare(b.textContent); //ordenar pelo nome
    else //caso contrario 
      return a_destaque && !b_destaque ? -1 : 1; //ordenar pelo destaque
  });
  
  for (let i = 0; i < listaOrdenada.length; i++) {
      //mover o elemento no html para o sitio correto de acordo com a ordenação
      listaOrdenada[i].parentNode.appendChild(listaOrdenada[i]); 
  }
}
.destaque {
  background-color:cyan;
}

.destaque:after {
  content:' (destaque)';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>Cliquenositemsparadestacar<ulclass="lista">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
  <li>Item 6</li>
  <li>Item 7</li>
  <li>Item 8</li>
<ul>
    
26.01.2018 / 03:07