2

I have a vh based website with elements I want to show when a certain vh has been scrolled. I tried using an if statement with a variable for distance scrolled, but it doesn't update constantly so it doesn't work:

var distancePX = $(window).scrollTop();
var windowHeight = $(window).height();
var distanceVH = scroll/height * 100;
if (distance >= 170) {
    //ACTIONS
};

What can I use to make a constantly updating version of above?

user7548189
  • 996
  • 6
  • 15
  • 30
  • You can see some examples here: [javascript: detect scroll end](http://stackoverflow.com/questions/3962558/javascript-detect-scroll-end/24808540#24808540), or [How can I determine the direction of a jQuery scroll event](http://stackoverflow.com/questions/4326845/how-can-i-determine-the-direction-of-a-jquery-scroll-event/24815216#24815216) – jherax Apr 23 '17 at 16:32
  • See [jQuery trigger when 2/3s of div are in viewport](http://stackoverflow.com/questions/29140800/jquery-trigger-when-2-3s-of-div-are-in-viewport/29142018#29142018) – guest271314 Apr 23 '17 at 16:42

2 Answers2

2

Using pure JS, you could use the onscroll event and bind it to the body. Here's an example:

HTML

<body onscroll="myFunction()">
  ...
</body>

JS

var distancePX = $(window).scrollTop();
var windowHeight = $(window).height();
var distanceVH = scroll/height * 100;

function myFunction() {
  if (distance >= 170) {
    //ACTIONS
  }
}

You can also use jQuery's scroll() method if you prefer a non-markup solution. With this method, you just place your if statement inside a scroll() function. Here's an example:

var distancePX = $(window).scrollTop();
var windowHeight = $(window).height();
var distanceVH = scroll/height * 100;

$("body").scroll(function(){
  if (distance >= 170) {
    //ACTIONS
  }
});

Hope this helps!

Hudson Taylor
  • 1,142
  • 2
  • 10
  • 30
0

Jquery Code

$(window).scroll(function(){
            if ($(this).scrollTop() >= 170) {
                //actions...
            } else {
                //actions...
            }
        });
blecaf
  • 1,625
  • 1
  • 8
  • 13