Correct way to get Scroll Position - javascript

In my application, I want to determine the current scroll position, so I have been using this to do so (source: https://www.codegrepper.com/code-examples/javascript/get+current+scroll+position+javascript)
window.pageYOffset || document.documentElement.scrollTop
Problem: When I console.log this, it only returns 0 when the page is not positioned and the top.
Question: Is there an alternative way to get the current scroll position?

Try window.scrollY.
The read-only scrollY property of the Window interface returns the
number of pixels that the document is currently scrolled vertically.
https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollY

recently i had the same problem. So in order to get the position as a percentage I end up do the following
window.addEventListener("scroll", function() {
const maxHeight = document.body.scrollHeight - window.innerHeight;
console.log((window.pageYOffset * 100) / maxHeight);
});
We subtract window.innerHeight from document.body.scrollHeight besause window.pageYOffset represents the top of the viewport. So in order for window.pageYOffset to match document.body.scrollHeight we do the above subtraction.
PS.: The above returns a float number. you can use parseInt(...) to convert it to integer if you'd like.

Related

How would I go about calculating the window toolbar area height?

So I'm trying to get the height of the top toolbar area as shown in the image. I'm aware of window.outerHeight - window.innerHeight but that also includes the bottom status bar area, giving me an innacurate number.
How would I go about calculating just the top section height?
Any help is appreciated.
So I figured out a hacky way to do it. You have to trigger a pointerEvent and get the screenY and clientY of the mouse position. Subtract the clientY position from the screenY position. This will then give you the top viewport screenY position. Then you subtract the window.screenY from the top viewport screenY position and this will give you the tab\toolbar\bookmark height.
When testing the code snippet, use the JSFiddle link below to run it in a full view. Running it on here will return an inaccurate result.
https://jsfiddle.net/Pending/y7jmf8r5/show
document.querySelector('button').addEventListener('pointerup', (e) => {
let toolbarHInaccurate = window.outerHeight - window.innerHeight;
let toolbarH = e.screenY - e.clientY - window.screenY;
console.log('Toolbar Height Innacurate:', toolbarHInaccurate + 'px');
console.log('Toolbar Height Actual:', toolbarH + 'px');
})
<button>Get Toolbar Height</button>
Measured, actual pixels: 114px
Result from toolbarH in code snippet: 114px
I'm using Windows 10 and window.outerHeight - window.innerHeight returned 120px which is inaccurate, but as stated by xyz, when he used that, it was accurate on his mac.

How can I control a minimum and maximum numeric value to be displayed based on scroll starting from a specific point on the page?

I am trying to display a number that begins to increase when the user gets to an element on the page and then will increase the further down the page they scroll to a maximum number, but the the number will also decrease back to the original number if they scroll up the page.
So far I am only able to make the function start from 0 and increase or decrease on scroll using 'window.scrollY'. Is there a way to set a minimum and maximum? Or is there a more elegant solution?
Using the example from this thread: Increase/Decrease variable on scroll
$("document").ready(function(){
$(window).scroll(function(){
let scrollValue = window.scrollY;
let num = $("#num");
num.html(scrollValue);
});
});
<span id="num"></span>
I don't exactly know if this is what you are looking for, but you could maybe map that variable to a different scale? I found this function:
const scale = (inputY, yRange, xRange) => {
const [xMin, xMax] = xRange;
const [yMin, yMax] = yRange;
const percent = (inputY - yMin) / (yMax - yMin);
const outputX = percent * (xMax - xMin) + xMin;
return outputX;
};
So if your scroll variable ranges from 0 - window.innerHeight and you want it to range between 0 and 10, you could use scale(window.scrollY, [0, window.innerheight], [0, 10]). This should work.
Let me give you some hints:
Element.scrollHeight returns the scroll height of any element. To get the height of the whole page, use this method on the root <html> or <body> element.
window.innerHeight returns the height of the viewport (window).
When the user has scrolled to the bottom of the page, the scrollY value would be html.scrollHeight - innerHeight because scrollY is the top of the viewport and scrollHeight is the bottom of the viewport.
I'll leave the rest up to you.
Good luck!
I don't know exactly what are you trying to do. However, I think you may want to try out: https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's viewport.

jQuery get current view position from top

I wish to check if my current element is in view or not. I use this condition to check that:
if ($(window).scrollTop() > $('.element').offset().top) {
//show
}
But problem is that $(window).scrollTop() is giving different results on different browser height (I'm using FireFox, first number is .scrollTop(), second - .offset().top):
now I just reduce height of firebug (so scroll bar is decreased in size):
So I can't use $(window).scrollTop() to get how mush I have scrolled in page.
Any other way how to define if element is in view?
You will need to consider these 4 base values:
Window's height
Window's scroll top
Element's offset top
Element's height
Based on that, you will have:
var windowHeight = $(window).height();
var windowScrollTop = $(window).scrollTop();
var elementHeight = $(".element").height();
var elementOffsetTop = $(".element").offset().top;
if ((elementOffsetTop <= windowScrollTop + windowHeight) && (elementOffsetTop + elementHeight >= windowScrollTop))
console.log('Visible on viewport');
Note that with this algorithm, you will be able to check if the element is visible on the viewport, independent of its height, and most importantly, considering the case when you scroll the window beyond the element.
It will say that the element is visible when the highest part or the lowest part of the element is shown on viewport.

get value of offset() and divide it by factor of windowheight

ive the following problem:
on window resize im fireing some events and one of them is this:
var height = $(window).height()
var getfactor = $('.second').offset().left/height
var getleft = getfactor*height
with this im doing:
$('.second').css('left', getleft);
but on window resize its always on the same position, and no left is been manipulated.
If I'm reading your code correctly you are essentially doing the following:
var getleft = ($('.second').offset().left / $(window).height()) * $(window).height();
Dividing by a number and then multiplying by that same number is going to cancel out any modification to the original left offset. You are essentially resetting the offset to its initial value every time the window is resized.

Javascript: How to calculate the exact position of the viewport?

My problem is I need to get the position of the viewport relative to the extent of the entire document. I am only concerned with Firefox.
My issue is that everything I have read says that:
viewport height is window.innerHeight
scroll position is window.pageYOffset
document total height is document.height
So, I would expect that if I scrolled to the bottom of a page that
window.innerHeight + window.pageYOffset == document.height
But it doesn't! Can someone please explain to me why this is?
When scrolling all the way to the bottom, this thould return true
window.innerHeight + window.pageYOffset == document.documentElement.scrollHeight
Document.height can be misleading because it is sometimes set to 100% in the CSS, which messes it up.

Categories

Resources