How to use vh units instead of pixels for .scrolltop functions

I have a menu bar whose class I want to change after users scroll to the next div, the div is 100vh. The function below only works with screens of my size, less or more animation will run sooner or later.

How do I make the units this function uses vh? Thanks to

  $(window).scroll(function() {    
var scroll = $(window).scrollTop();
if (scroll >= 600) {   <---- change to vh units not px-----
    $(".home").removeClass("open");
}

      

+3


source to share


4 answers


100vh is the actual view height of this screen. so when using screens of different sizes, 100vh will be calculated for a different size.



-1


source


You can create an invisible anchor at the height you want the bottom div to reach before changing the menu class. Place this anchor element with vh and to test the scroll function if the bottom div has crossed the anchor element.

CSS

#fixed {
    position: fixed;
    top: 10vh;         /*or whatever height you want*/
}

      



JS:

$(window).scroll(function() {   

    var test = $('#fixed').offset().top;
    var lowerDivPosition = $('#lowerDiv').offset().top;

    if (lowerDivPosition >= test) { 
        $(".home").removeClass("open");
    };
});

      

0


source


For everyone who comes across this. I did this by simply creating a variable that gets the height of the viewport (which will return a value in pixels) and then use that variable in a function.

My script will scroll down 1vh

var scrollBtn = $('#scrolldown');
var windowHeight = $(window).height(); // value in pixels
scrollBtn.click(function(){
  $('html, body').animate({
    scrollTop: $(window).scrollTop() + windowHeight
  },2000);
});

      

For this question, the solution would be something like this:

$(window).scroll(function() {    
  var windowHeight = $(window).height();
  var scroll = $(window).scrollTop();
  if (scroll >= windowHeight) {
    $(".home").removeClass("open");
  }
});

      

0


source


Use window.innerHeight

and multiply it by a fraction. For example, if you want to use 60 vh (window.innerHeight)*0.6

.

I'm not familiar with jQuery, but with vanillaJS this would be

if (window.pageYOffset > window.innerHeight)

      

0


source







All Articles