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");
}
source to share
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");
};
});
source to share
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");
}
});
source to share