Capture first scroll value

0

What I am doing: When I do scrolling on my page I capture the position of the scroll. But how would you do if you wanted to capture the first value of the scroll? That is, the first scroll I made, I want to save that value in a variable (and that does not change) .. Until now I can not get it because I always return the updated value, according to the position where I am.

    
asked by user104554 16.11.2018 в 22:42
source

1 answer

0

For more elaborate purposes I would say that you would look how to define the property of an object as immutable ... but in this case do not complicate and save it in a separate variable .

Suppose that today you have a listener listening to the scroll. It is not a very efficient example but it serves:

jQuery(window).scroll(function() { 
   var scrollActual = jQuery(this).scrollTop();
   console.log(scrollActual); 
});

If you define a variable a priori outside the scope of the handler, and you give it a null value or you just do not give it value, inside the handler you can know if it has been set (in which case you do not touch it) or if it is the first scroll (in which case you set it up)

var primerScroll = null;

jQuery(window).scroll(function() { 
   var scrollActual = jQuery(this).scrollTop();
   if(primerScroll === null ) {
      primerScroll = scrollActual;
   }
   console.log(scrollActual); 
});

The if is only met the first time.

Note

I assumed you were using jQuery, I'm going to edit the answer using vanilla but I can not do it right away.

    
answered by 17.11.2018 в 00:29