Anfa A
Anfa A

Reputation: 313

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

I have a menu bar who's class I want to change after a users scrolls to the next div, the div is 100vh tall. The function below works only with screens my size, anything smaller or bigger the animation will go to early or too late.

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

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

Upvotes: 8

Views: 11063

Answers (4)

Przemex Przemax
Przemex Przemax

Reputation: 63

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

I'm not familliar with jQuery, but with vanillaJS it would be

if (window.pageYOffset > window.innerHeight)

Upvotes: 5

Mosh
Mosh

Reputation: 471

For anyone coming across this. What I did for this was simply create a variable that gets the height of the viewport (which will return a value in pixels) and then use that variable in the function.

My script would 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");
  }
});

Upvotes: 2

BarthesSimpson
BarthesSimpson

Reputation: 969

You could create an invisible fixed element at the height you want the lower div to reach before changing the menu class. Position this fixed element using vh and for your scroll function test if the lower div has crossed the fixed 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");
    };
});

Upvotes: 0

jbg
jbg

Reputation: 476

100vh is the actual view height of that screen. so when you use different size screens 100vh will be calculated to a different size.

Upvotes: -1

Related Questions