How to capture the id of each row in a scrollable list?

0

I have a list of 200 lines, and each line has its id.

I would like to capture with the javascript, the id of each line when descending the page.

The list is set up like this:

<ol id="noticias">
    <li id="geral" class="area">
      Conteudo
    </li>
    <li id="esportes" class="area">
      Conteudo
    </li>
    <li id="mundial" class="area">
      Conteudo
    </li>
    <li id="tecnologia" class="area">
      Conteudo
    </li>
</ol>

Trying to explain otherwise.

I've mounted an array, in which, each entry represents a row in my list. In each entry there are two fields, one with the height of the line and another with the id of the line.

You're like this:

var lists =     [45, 'news'],     [50, 'technology'],     [100, 'world'] ];

For each page scroll, the program captures the height of the body, and with the value of the height of the body, it analyzes in which field I am in the array

Solution:

I got it by using this function:

$(window).on("scroll resize", function() {

    var altura_body = $(window).scrollTop();

    for (var i = 0; i <= numero_de_linhas; i++) {
        if (altura_body >= listas[i][0] && altura_body <= listas[i + 1][0]) {
            $(".mostra_id").html(listas[i][1]);
        }
    }
});
    
asked by anonymous 30.06.2018 / 03:38

1 answer

1

I did this with pure JS, since the jQuery tag was not marked (explanations in code):

document.addEventListener("scroll", function(){
   var lista = document.querySelectorAll("#noticias li");
   for(var x=0; x<lista.length; x++){
      var elTopo = lista[x].offsetTop; // distância relativa do elemento ao topo
      var scrlTopo = window.pageYOffset; // scroll da janela
      var altJanela = window.innerHeight; // altura da janela
      var distance = elTopo-scrlTopo; // distância absoluta do elemento ao topo
      if(distance <= altJanela){ // verifico se o elemento apareceu na janela
         document.querySelector(".mostra_id").innerHTML = lista[x].id;
      }else if(lista[0].offsetTop-scrlTopo >= altJanela){ // se o primeiro elemento da lista sumir
         document.querySelector(".mostra_id").innerHTML = ''; // apaga o conteúdo da div
      }
   }
});
.mostra_id{
   position: fixed;
   top: 30px;
   color: red;
}
<div class="mostra_id"></div>
Role a tela
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<ol id="noticias">
    <li id="geral" class="area">
      geral
    </li>
    <li id="esportes" class="area">
      esportes
    </li>
    <li id="mundial" class="area">
      mundial
    </li>
    <li id="tecnologia" class="area">
      tecnologia
    </li>
</ol>
    
30.06.2018 / 06:12