Determine if user has scrolled 25% in react [duplicate] - javascript

How can I find out what percentage of the vertical scrollbar a user has moved through at any given point?
It's easy enough to trap the onscroll event to fire when the user scrolls down the page, but how do I find out within that event how far they have scrolled? In this case, the percentage particularly is what's important. I'm not particularly worried about a solution for IE6.
Do any of the major frameworks (Dojo, jQuery, Prototype, Mootools) expose this in a simple cross-browser compatible way?

Oct 2016: Fixed. Parentheses in jsbin demo were missing from answer. Oops.
Chrome, Firefox, IE9+. Live Demo on jsbin
var h = document.documentElement,
b = document.body,
st = 'scrollTop',
sh = 'scrollHeight';
var percent = (h[st]||b[st]) / ((h[sh]||b[sh]) - h.clientHeight) * 100;
As function:
function getScrollPercent() {
var h = document.documentElement,
b = document.body,
st = 'scrollTop',
sh = 'scrollHeight';
return (h[st]||b[st]) / ((h[sh]||b[sh]) - h.clientHeight) * 100;
}
If you prefer jQuery (original answer):
$(window).on('scroll', function(){
var s = $(window).scrollTop(),
d = $(document).height(),
c = $(window).height();
var scrollPercent = (s / (d - c)) * 100;
console.clear();
console.log(scrollPercent);
})
html{ height:100%; }
body{ height:300%; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

I think I found a good solution that doesn't depend on any library:
/**
* Get current browser viewpane heigtht
*/
function _get_window_height() {
return window.innerHeight ||
document.documentElement.clientHeight ||
document.body.clientHeight || 0;
}
/**
* Get current absolute window scroll position
*/
function _get_window_Yscroll() {
return window.pageYOffset ||
document.body.scrollTop ||
document.documentElement.scrollTop || 0;
}
/**
* Get current absolute document height
*/
function _get_doc_height() {
return Math.max(
document.body.scrollHeight || 0,
document.documentElement.scrollHeight || 0,
document.body.offsetHeight || 0,
document.documentElement.offsetHeight || 0,
document.body.clientHeight || 0,
document.documentElement.clientHeight || 0
);
}
/**
* Get current vertical scroll percentage
*/
function _get_scroll_percentage() {
return (
(_get_window_Yscroll() + _get_window_height()) / _get_doc_height()
) * 100;
}

This should do the trick, no libraries required:
function currentScrollPercentage()
{
return ((document.documentElement.scrollTop + document.body.scrollTop) / (document.documentElement.scrollHeight - document.documentElement.clientHeight) * 100);
}

These worked for me perfectly in Chrome 19.0, FF12, IE9:
function getElementScrollScale(domElement){
return domElement.scrollTop / (domElement.scrollHeight - domElement.clientHeight);
}
function setElementScrollScale(domElement,scale){
domElement.scrollTop = (domElement.scrollHeight - domElement.clientHeight) * scale;
}

A Typescript implementation.
function getScrollPercent(event: Event): number {
const {target} = event;
const {documentElement, body} = target as Document;
const {scrollTop: documentElementScrollTop, scrollHeight: documentElementScrollHeight, clientHeight} = documentElement;
const {scrollTop: bodyScrollTop, scrollHeight: bodyScrollHeight} = body;
const percent = (documentElementScrollTop || bodyScrollTop) / ((documentElementScrollHeight || bodyScrollHeight) - clientHeight) * 100;
return Math.ceil(percent);
}

If you're using Dojo, you can do the following:
var vp = dijit.getViewport();
return (vp.t / (document.documentElement.scrollHeight - vp.h));
Which will return a value between 0 and 1.

This question has been here for a long time, I know, but I stumbled onto it while trying to solve the same problem. Here is how I solved it, in jQuery:
First, I wrapped the thing I wanted to scroll in a div (not semantic, but it helps). Then set the overflow and height on the wrapper.
<div class="content-wrapper" style="overflow: scroll; height:100px">
<div class="content">Lot of content that scrolls</div>
</div>
Finally I was able to calculate the % scroll from these metrics:
var $w = $(this),
scroll_top = $w.scrollTop(),
total_height = $w.find(".content").height(),
viewable_area = $w.height(),
scroll_percent = Math.floor((scroll_top + viewable_area) / total_height * 100);
Here is a fiddle with working example: http://jsfiddle.net/prEGf/

Everyone has great answers, but I just needed an answer as one variable. I didn't need an event listener, I just wanted to get the scrolled percentage. This is what I got:
const scrolledPercentage =
window.scrollY / (document.documentElement.scrollHeight - document.documentElement.clientHeight)
document.addEventListener("scroll", function() {
const height = window.scrollY / (document.documentElement.scrollHeight - document.documentElement.clientHeight)
document.getElementById("height").innerHTML = `Height: ${height}`
})
.container {
position: relative;
height: 200vh;
}
.sticky-div {
position: sticky;
top: 0;
}
<!DOCType>
<html>
<head>
</head>
<body>
<div id="container" class="container">
<div id="height" class="sticky-div">
Height: 0
</div>
</div>
</body>

First attach an event listener to some document you want to keep track
yourDocument.addEventListener("scroll", documentEventListener, false);
Then:
function documentEventListener(){
var currentDocument = this;
var docsWindow = $(currentDocument.defaultView); // This is the window holding the document
var docsWindowHeight = docsWindow.height(); // The viewport of the wrapper window
var scrollTop = $(currentDocument).scrollTop(); // How much we scrolled already, in the viewport
var docHeight = $(currentDocument).height(); // This is the full document height.
var howMuchMoreWeCanScrollDown = docHeight - (docsWindowHeight + scrollTop);
var percentViewed = 100.0 * (1 - howMuchMoreWeCanScrollDown / docHeight);
console.log("More to scroll: "+howMuchMoreWeCanScrollDown+"pixels. Percent Viewed: "+percentViewed+"%");
}

My two cents, the accepted answer in a more "modern" way. Works back to IE9 using #babel/preset-env.
// utilities.js
/**
* #param {Function} onRatioChange The callback when the scroll ratio changes
*/
export const monitorScroll = onRatioChange => {
const html = document.documentElement;
const body = document.body;
window.addEventListener('scroll', () => {
onRatioChange(
(html.scrollTop || body.scrollTop)
/
((html.scrollHeight || body.scrollHeight) - html.clientHeight)
);
});
};
Usage:
// app.js
import { monitorScroll } from './utilities';
monitorScroll(ratio => {
console.log(`${(ratio * 100).toFixed(2)}% of the page`);
});

I reviewed all of these up there but they use more complex approaches to solve. I found this through a mathematical formula; brief.
The formula goes Value/Total * 100. Say Total is 200 u wanna know the percentage of 100 out of 200, you do it 100/200 * 100% = 50% (the value)
pageYOffset = The vertical scroll count without including borders. When you scroll down to bottom you get the maximum count.
offsetHeight = The total height of the page including borders!
clientHeight = The height in pixels without borders but not to the end of content!
When u scroll to bottom u get pageyoffset of 1000 for example, whereas offsetHeight of 1200 and clientHeight of 200. 1200 - 200(clientheight) now u get paggeYOffset value in offsetHeight and so scrollPosition300(300 of 1000)/1000 * 100 = 30%.
`pageOffset = window.pageYOffset;
pageHeight = document.documentElement.offsetHeight;
clientHeight = document.documentElement.clientHeight;
percentage = pageOffset / (pageHeight - clientHeight) * 100 + "%";
console.log(percentage)`
The reason why we must do offsetHeight - clientHeight it is because client heights shows all the available content in px without borders, and offsetheight shows the available content including borders, whereas pageYOffset counts the scrolls made; The scrollbar is quite long to count the whole windows it counts the scrolls itself until reaches the end, the available space in scrollbar is in px pageYOffset, so to reach that number you substract offsetHeight - clientHeight to bring to the lower value of pageYOffset.
i'll update when i get on pc, please leave a comment to make it clear so i don't forget! Thanks :)

Using jQuery
$(window).scrollTop();
will get you the scroll position, you can then work out from there what the percentage is based on the window height.
There is also a standard DOM property scrollTop that you can use like document.body.scrollTop however I'm not sure how this behaves cross-browser, I would assume if there are inconsistencies then the jQuery method accounts for these.

var maxScrollTop = messages.get(0).scrollHeight - messages.height();
var scroll = messages.scrollTop() / maxScrollTop; // [0..1]

I found a way to correct a previous answer, so it works in all cases. Tested on Chrome, Firefox and Safari.
(((document.documentElement.scrollTop + document.body.scrollTop) / (document.documentElement.scrollHeight - document.documentElement.clientHeight) || 0) * 100)

Related

Scroll by given vertical scroll percentage in JavaScript

I have X and Y scroll values in percentage (values spanning from 0 to 100) and I want to scroll the page to that location. I am receiving the percentage values from an API call.
function scrollPageByGivenPercentage(percentageX, percentageY) {
// ... scroll by percentage ...
//window.scrollTo(percentageX, percentageY);
}
The above function scrolls in pixels and it doesn't do the job. What I tried using is this:
function scrollPageByGivenPercentage(percentageX, percentageY) {
var yScrollInPx = document.body.documentElement.clientHeight * percentageY;
window.scrollTo(0, yScrollInPx);
}
My guess is clientHeight is the wrong property. Tried offsetHeight as well.
I get the calculate the percentages from this question:
I have this function to receive the current scroll value in percentage:
function getScrollPercent() {
var h = document.documentElement,
b = document.body,
st = 'scrollTop',
sh = 'scrollHeight';
return (h[st] || b[st]) / ((h[sh] || b[sh]) - h.clientHeight) * 100;
}
Get the total height of the document, work out the percentage you need in px then apply that to window.scrollTo(). Try this:
var scrollYPercent = 0.25;
var scrollYPx = document.documentElement.scrollHeight * scrollYPercent;
window.scrollTo(0, scrollYPx);
html, body { height: 1000px; }
p { margin-top: 400px; }
<p>Note the scroll position -></p>

JavaScript calculate with viewport width/height

I am trying to set a responsive point in my mobile Webview and did this:
var w = window.innerWidth-40;
var h = window.innerHeight-100;
This works great so far. But the values -40 and -100 are not in the viewport scaling height and width.
When I do this:
var w = window.innerWidth-40vw;
var h = window.innerHeight-100vh;
as it should be to stay responsive and relative to the viewport - the JS does not work anymore.
I think vh and vw works only in CSS ?
How can I achieve this in JS ?
Pleas no JQuery solutions - only JS!
Thanks
Based on this site you can use the following util functions to calculate your desired values as a function of a percent of screen width or height:
function vh(percent) {
var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
return (percent * h) / 100;
}
function vw(percent) {
var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
return (percent * w) / 100;
}
function vmin(percent) {
return Math.min(vh(percent), vw(percent));
}
function vmax(percent) {
return Math.max(vh(percent), vw(percent));
}
console.info(vh(20), Math.max(document.documentElement.clientHeight, window.innerHeight || 0));
console.info(vw(30), Math.max(document.documentElement.clientWidth, window.innerWidth || 0));
console.info(vmin(20));
console.info(vmax(20));
I used this incredible question in my code!
Try this:
function getViewport() {
var viewPortWidth;
var viewPortHeight;
// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
if (typeof window.innerWidth != 'undefined') {
viewPortWidth = window.innerWidth,
viewPortHeight = window.innerHeight
}
// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
else if (typeof document.documentElement != 'undefined'
&& typeof document.documentElement.clientWidth !=
'undefined' && document.documentElement.clientWidth != 0) {
viewPortWidth = document.documentElement.clientWidth,
viewPortHeight = document.documentElement.clientHeight
}
// older versions of IE
else {
viewPortWidth = document.getElementsByTagName('body')[0].clientWidth,
viewPortHeight = document.getElementsByTagName('body')[0].clientHeight
}
return [viewPortWidth, viewPortHeight];
}
Reference: http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/
Problem is that JS does not have 40vh, calculate how much pixels is 40vh first to use it. It will throw error when doing 1000 - 40vh
40vh means 40 % of viewport height. So window.innerHeight * 0.4 == 40vh
Also there is no such thing as wh, only vh (% of viewport height)
The simplest way to do this, if you can fully edit the page, is to make a css class that has -40vw and -100vh like so:
CSS:
.class{
width: -40vw;
height: -100vh;
}
JS:
element.classList.add("class");
Note: "classList" is not supported in Internet Explorer 9. If you want it to work in all browsers, use this for JS instead:
function myFunction() {
var element, name, arr;
element = document.getElementById("myDIV");
name = "mystyle";
arr = element.className.split(" ");
if (arr.indexOf(name) == -1) {
element.className += " " + name;
}
}
you just need to surround it in quotes I think.
var w = window.innerWidth = "40vw"
var w = window.innerWidth = "40vw"
this is my solve with you can use CSS;
// calc dynamic customer device height/width
let vh = window.innerHeight * 0.01,
vw = window.innerWidth * 0.01;
document.documentElement.style.setProperty('--vh', `${vh}px`);
document.documentElement.style.setProperty('--vw', `${vw}px`);
How to use in CSS ?
If you will use 100vh or 100vw with this method, you should set 100vh/100vw for uncompatible browser.
Examples;
.wrapper{
height: 100vh; /* Fallback for browsers that do not support Custom Properties */
height: calc(var(--vh, 1vh) * 100);
}
.slide-container{
height: calc(var(--vh, 1vh) * 100 - var(--menuHeight) - var(--footerHeight));
}
.little-image{
width: calc(var(--vw, 1vw) * 5);
margin-bottom: calc(var(--vh, 1vh) * 1);
}
/* and more.. */
This isn't a universal solution, but it's a much simpler implementation if you're working with a page that is always 100% displayed within the viewport (ie, if the body doesn't have to be scrolled and always matches the window width and height).
let vh = document.body.getBoundingClientRect().height;
This sets the vh variable to the pixel value of the document body with just one line of code.
Useful for game dev and other scenarios where you have the body affixed to the viewport.
get vmin in px
function vmin(){
return window.innerHeight < window.innerWidth ? window.innerHeight: window.innerWidth;
}

Current Cursor Position in Percentages

How to get current cursor position (xy coordinates) in percentages?
<script type="text/javascript">
$(document).ready(function(){
$(document).mousemove(function(getCurrentPos){
var xCord = getCurrentPos.pageX;
var yCord = getCurrentPos.pageY;
console.log(xCord+" "+yCord);
});
});
</script>
I want the total width of the page (x coord) in percentage to deal with responsive layout?
You can put in a jquery .width() call, something like:
xPercent = xCord / $( document ).width() * 100;
console.log( xPercent + "%" );
(also note jQuery .height() call)
pageY will take into account the offset of your browser header bar, you want to use clientY instead. In the following code, you will have xPercent and yPercent that go from 0 to 1 (multiply by 100 if you want an actual percentage).
$(document).mousemove(function(getCurrentPos){
var xCord = getCurrentPos.clientX;
var yCord = getCurrentPos.clientY;
var xPercent = xCord/window.innerWidth;
var yPercent = yCord/window.innerHeight;
});
Or since you are using jQuery, $(window).width() and $(window).height() are better for cross-browser concerns.
use: getCurrentPos.view.outerHeight& getCurrentPos.view.outerWidthto get the actual size of height&width and then calc the percentage with what you already got.
I know this is super old, and has an accepted answer, but I figured since it pops up on Google I'd provide a non-Jquery way, simple as it may be.
I made this CodePen for easy reference: https://codepen.io/DouglasGlover/pen/eYNPjwg
HTML (for displaying numbers):
Position X: <span id="posX">NaN</span>%<br/>
Position Y: <span id="posY">NaN</span>%
CSS (to make body 100% height & width for the demo):
body {
margin: 0;
overflow: hidden;
width: 100vw;
height: 100vh;
background: skyblue;
font-weight: bold;
font-family: arial;
}
Javascript (the magic):
// Container and displays
const container = document.querySelector("body");
let posXDisplay = document.getElementById("posX");
let posYDisplay = document.getElementById("posY");
// On mousemove
container.addEventListener("mousemove", (e)=> {
// Do math
xPercent = parseInt(e.pageX / window.innerWidth * 100);
yPercent = parseInt(e.pageY / window.innerHeight * 100);
// Display numbers
posXDisplay.innerText = xPercent;
posYDisplay.innerText = yPercent;
});

Get the visible height of a div with jQuery

I need to retrieve the visible height of a div within a scrollable area. I consider myself pretty decent with jQuery, but this is completely throwing me off.
Let's say I've got a red div within a black wrapper:
In the graphic above, the jQuery function would return 248, the visible portion of the div.
Once the user scrolls past the top of the div, as in the above graphic, it would report 296.
Now, once the user has scrolled past the div, it would again report 248.
Obviously my numbers aren't going to be as consistent and clear as they are in this demo, or I'd just hard code for those numbers.
I have a bit of a theory:
Get the height of the window
Get the height of the div
Get the initial offset of the div from the top of the window
Get the offset as the user scrolls.
If the offset is positive, it means the top of the div is still visible.
if it's negative, the top of the div has been eclipsed by the window. At this point, the div could either be taking up the whole height of the window, or the bottom of the div could be showing
If the bottom of the div is showing, figure out the gap between it and the bottom of the window.
It seems pretty simple, but I just can't wrap my head around it. I'll take another crack tomorrow morning; I just figured some of you geniuses might be able to help.
Thanks!
UPDATE: I figured this out on my own, but looks like one of the answers below is more elegant, so I'll be using that instead. For the curious, here's what I came up with:
$(document).ready(function() {
var windowHeight = $(window).height();
var overviewHeight = $("#overview").height();
var overviewStaticTop = $("#overview").offset().top;
var overviewScrollTop = overviewStaticTop - $(window).scrollTop();
var overviewStaticBottom = overviewStaticTop + $("#overview").height();
var overviewScrollBottom = windowHeight - (overviewStaticBottom - $(window).scrollTop());
var visibleArea;
if ((overviewHeight + overviewScrollTop) < windowHeight) {
// alert("bottom is showing!");
visibleArea = windowHeight - overviewScrollBottom;
// alert(visibleArea);
} else {
if (overviewScrollTop < 0) {
// alert("is full height");
visibleArea = windowHeight;
// alert(visibleArea);
} else {
// alert("top is showing");
visibleArea = windowHeight - overviewScrollTop;
// alert(visibleArea);
}
}
});
Calculate the amount of px an element (height) is in viewport
Fiddle demo
This tiny function will return the amount of px an element is visible in the (vertical) Viewport:
function inViewport($el) {
var elH = $el.outerHeight(),
H = $(window).height(),
r = $el[0].getBoundingClientRect(), t=r.top, b=r.bottom;
return Math.max(0, t>0? Math.min(elH, H-t) : Math.min(b, H));
}
Use like:
$(window).on("scroll resize", function(){
console.log( inViewport($('#elementID')) ); // n px in viewport
});
that's it.
jQuery .inViewport() Plugin
jsFiddle demo
from the above you can extract the logic and create a plugin like this one:
/**
* inViewport jQuery plugin by Roko C.B.
* http://stackoverflow.com/a/26831113/383904
* Returns a callback function with an argument holding
* the current amount of px an element is visible in viewport
* (The min returned value is 0 (element outside of viewport)
*/
;(function($, win) {
$.fn.inViewport = function(cb) {
return this.each(function(i,el) {
function visPx(){
var elH = $(el).outerHeight(),
H = $(win).height(),
r = el.getBoundingClientRect(), t=r.top, b=r.bottom;
return cb.call(el, Math.max(0, t>0? Math.min(elH, H-t) : Math.min(b, H)));
}
visPx();
$(win).on("resize scroll", visPx);
});
};
}(jQuery, window));
Use like:
$("selector").inViewport(function(px) {
console.log( px ); // `px` represents the amount of visible height
if(px > 0) {
// do this if element enters the viewport // px > 0
}else{
// do that if element exits the viewport // px = 0
}
}); // Here you can chain other jQuery methods to your selector
your selectors will dynamically listen to window scroll and resize but also return the initial value on DOM ready trough the first callback function argument px.
Here is a quick and dirty concept. It basically compares the offset().top of the element to the top of the window, and the offset().top + height() to the bottom of the window:
function getVisible() {
var $el = $('#foo'),
scrollTop = $(this).scrollTop(),
scrollBot = scrollTop + $(this).height(),
elTop = $el.offset().top,
elBottom = elTop + $el.outerHeight(),
visibleTop = elTop < scrollTop ? scrollTop : elTop,
visibleBottom = elBottom > scrollBot ? scrollBot : elBottom;
$('#notification').text(`Visible height of div: ${visibleBottom - visibleTop}px`);
}
$(window).on('scroll resize', getVisible).trigger('scroll');
html,
body {
margin: 100px 0;
}
#foo {
height: 1000px;
background-color: #C00;
width: 200px;
margin: 0 auto;
}
#notification {
position: fixed;
top: 0;
left: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="foo"></div>
<div id="notification"></div>
The logic can be made more succinct if necessary, I've just declared separate variables for this example to make the calculation as clear as I can.
Here is a version of Rory's approach above, except written to function as a jQuery plugin. It may have more general applicability in that format. Great answer, Rory - thanks!
$.fn.visibleHeight = function() {
var elBottom, elTop, scrollBot, scrollTop, visibleBottom, visibleTop;
scrollTop = $(window).scrollTop();
scrollBot = scrollTop + $(window).height();
elTop = this.offset().top;
elBottom = elTop + this.outerHeight();
visibleTop = elTop < scrollTop ? scrollTop : elTop;
visibleBottom = elBottom > scrollBot ? scrollBot : elBottom;
return visibleBottom - visibleTop
}
Can be called with the following:
$("#myDiv").visibleHeight();
jsFiddle
Here is the improved code for jquery function visibleHeight: $("#myDiv").visibleHeight();
$.fn.visibleHeight = function() {
var elBottom, elTop, scrollBot, scrollTop, visibleBottom, visibleTop, height;
scrollTop = $(window).scrollTop();
scrollBot = scrollTop + $(window).height();
elTop = this.offset().top;
elBottom = elTop + this.outerHeight();
visibleTop = elTop < scrollTop ? scrollTop : elTop;
visibleBottom = elBottom > scrollBot ? scrollBot : elBottom;
height = visibleBottom - visibleTop;
return height > 0 ? height : 0;
}

make DIV 100% width when scrollbar is # bottom with JQuery

Im trying to make a width DIV grow to 100% when the scrollbar is at the bottom,
and shrink to 0% when the scrollbar is at the top of the page.
I tried to make it like this :
$(document).ready(function () {
var myWidth = $(window).width();
var res = myWidth / 100;
var myHeight = $(document).height();
var myScreen = $(window).height();
$(window).scroll(function () {
var scrolling = $(window).scrollTop();
var myPrecentage = (scrolling + myScreen) / (myHeight );
console.log(myPrecentage);
$('#com1').css("width", ((myPrecentage) * 100) + "%");
});
});
I came across a problem, when I try to use the scrollTop, it doesnt calculate the screen height, so I alwayes start when the scrollTop is 0, about 20% of width.
have you got better idea how to tackle it ?
I may not have fully understood what you are trying to do, but it sounds like you want to compute % between 0 and 100% based on where you are in your scroll. (Perhaps you want to translate vertical action to horizontal graph representation.)
Your code works, and just needs minor adjustment. Right now you are computing % based on:
var myPrecentage = (scrolling + myScreen) / (myHeight );
What you want is:
var myPrecentage = scrolling / (myHeight - myScreen);
Which is same as:
$(window).scrollTop() / ($(document).height() - $(window).height());
(I should add, I'm using Chrome - behavior may differ across browsers.)
I think your current problem is that you're always starting off with the size of the view window. So unless the view is at 0, you'll always start with a < zero number. You only want to add scrolling and myScreen when the scrolling view has passed beyond the myScreen size.
http://jsfiddle.net/ufomammut66/C2aFH/
var myPrecentage;
if((scrolling - myScreen) < myScreen){
myPrecentage = (scrolling) / (myHeight );
} else {
myPrecentage = (scrolling + myScreen) / (myHeight );
}

Categories