Run function only once when scrolling

0

I want a function to be executed when it is between the beginning and the end of a section. This I already did and I show it below (but something is missing):

  var S1 = $( 'section:eq(0)' ).offset(  
  ).top; //OBTENGO LA POSICION VERTICAL DE LA PRIMERA SECCION
  var S2 = $( 'section:eq(1)' ).offset(  
  ).top; //OBTENGO LA POSICION VERTICAL DE LA SEGUNDA SECCION

  window.onscroll = function (  ) { 
 //CUANDO HAGO SCROLL EN LA PAGINA PASA ALGO

  //SI EL SCROLL ES MAYOR A LA SECCION NUMERO 1 Y MENOR A LA SECCION NUMERO 2, SE EJECUTA EL CODIGO
  if ( $( this ).scrollTop(  ) > S1  && $( this 
  ).scrollTop(  ) < S2 ) {
    alert( "hola" ) //A MODO DE EJEMPLO SOLO PONGO UN ALERT
  }

}

My code up there is very good. The problem is that this "alert" will be executed every time the user advances a pixel with the scroll top. That is, they will be many, but I only want one to be executed (when I enter between the limits of section one) and two ... can someone give me a hand please? My fear as always is to be executing unnecessary or repetitive code I already tried with SETTIMEOUT but it does not work because every time a new scroll is made the settimeout restarts

    
asked by user104554 17.11.2018 в 00:17
source

1 answer

0

You could place a flag which starts at 0, when between the onscroll event and your conditions are true you evaluate the flag. If the flag is 0, then you execute your code (in this case the alert ()) and the flag becomes 1. If the onscroll event is executed and your conditions are true again BUT the flag is different from 0, then you place it Do not do anything and go.

var S1 = $( 'section:eq(0)' ).offset().top; //OBTENGO LA POSICION VERTICAL DE LA PRIMERA SECCION
var S2 = $( 'section:eq(1)' ).offset().top; //OBTENGO LA POSICION VERTICAL DE LA SEGUNDA SECCION
var bandera = 0;
window.onscroll = function () { //CUANDO HAGO SCROLL EN LA PAGINA PASA ALGO
//SI EL SCROLL ES MAYOR A LA SECCION NUMERO 1 Y MENOR A LA SECCION NUMERO 2, SE EJECUTA EL CODIGO
if ( $( this ).scrollTop(  ) > S1  && $(this).scrollTop() < S2 ) {
    if(bandera==0){
      alert( "hola" ) //A MODO DE EJEMPLO SOLO PONGO UN ALERT
      bandera=1;
    }else{
    //No hacemos nada
    }

} 
else{ //tampoco hacemos nada
  }
}
    
answered by 18.11.2018 в 06:12