Reputation: 395
If I want to use this JavaScript command:
window.scrollBy(0,50);
It scrolls 50px down the page.
Is there a simple equivalent to scroll 50vh down the page? This doesn't work
window.scrollBy(0,50vh);
I saw this question here but is there a simpler way to do it?
Upvotes: 6
Views: 14505
Reputation: 1397
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
Reputation: 15566
scrollBy accepts value in pixels only.
1vh = 1/100 viewport height. So you can calculate it manually.
window.scrollBy(0, valueInVh * window.innerHeight/100);
Upvotes: 5
Reputation: 4291
AFAIK the JavaScript DOM APIs only give you pixel values. If you want "50vh" in pixels you can easily calculate it yourself:
// height in pixel
const height = window.innerHeight;
const vhPixels = height * 0.5
window.scrollBy(0, vhPixels);
Upvotes: 2
Reputation: 53709
You can divide the window.innerHeight
by 2
window.scrollBy(0, window.innerHeight / 2);
Upvotes: 16