how to get maximum scroll height for ion content? - javascript

I would like to calculate the current scroll percentage of my IonContent (it's an Ionic + React app)
The page layout looks like this:
<IonPage>
<IonHeader>
<IonToolbar>
<IonButtons slot="start">
<IonMenuButton />
</IonButtons>
<IonTitle>Page</IonTitle>
</IonToolbar>
</IonHeader>
<IonContentid="main-content"
scrollEvents={true}
onIonScroll={(ev) => {
// ToDo: calculate scroll percentage
console.log(ev.detail.scrollTop);
}}>
{// very long custom component
}
<IonFooter>
<IonLabel>Footer </IonLabel>
</IonFooter>
</IonContent>
</IonPage>
From the IonScroll event, I can read out the scrollTop which seems to be the current scroll position.
Now I need to get the maximal scrolling height of the IonContent.
Related questions are:
finding the maximum scroll position of a page
Cross-Browser Method to Determine Vertical Scroll Percentage in Javascript
how to calculate height of scroll content
The accepted answer from the first question seems to provide the most complete approach, by taking the max over a selection of scrolling height values:
var limit = Math.max( document.body.scrollHeight, document.body.offsetHeight,
document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight );
I've extended this by also adding:
document.scrollingElement.scrollHeight
The problem:
In my scenario, the maximum over these values is around 660. But the logging output from ev.detail.scrollTop goes up to 680.76.
I've connected the debug inspector and tried scrolling from the console, to see what would happen for scroll value around 660. I can still see the content move when scrolling from 660 to 680:
document.getElementById('main-content').scrollToPoint(0, 680);
How can I find the maximum scrolling coordinates?

I think I found the solution:
onIonScroll={async (ev) => {
const elem = document.getElementById("ion-content-id");
// the ion content has its own associated scrollElement
const scrollElement = await ( elem as any).getScrollElement()
const scrollPosition = ev.detail.scrollTop;
const totalContentHeight = scrollElement.scrollHeight;
const viewportHeight = elem.offsetHeight;
const percentage = scrollPosition / (totalContentHeight - viewportHeight);
console.log(percentage);
}}
I don't understand why this incompatibility was introduced though. Wouldn't it be possible to connect the scrollElement of the IonContent with document.scrollingElement? The standard is still a draft but implemented in all major browsers (expect IE).

Related

A method to determined can Scroll in X or Y [duplicate]

What's the fastest way of checking whether an element has scroll bars?
One thing of course is checking whether element is larger than its viewport, which can easily be done by checking these two values:
el.scrollHeight > el.offsetHeight || el.scrollWidth > el.offsetWidth
but that doesn't mean that it has scrollbars as well (so it can actually be scrolled by humans).
Question
How do I check for scrollbars in a 1 cross browser and 2 javascript only (as in no jQuery) way?
Javascript only, because I need as small overhead as possible, because I'd like to write a very fast jQuery selector filter
// check for specific scrollbars
$(":scrollable(x/y/both)")
// check for ANY scrollbar
$(":scrollable")
I suppose I'd have to check for overflow style settings but how do I do that in a cross browser way?
Additional edit
Not only overflow style settings. Checking whether an element has a scrollbar isn't as trivial as it seems. The first formula I've written above works fine when element doesn't have a border, but when it does (especially when border is of considerable width), offset dimension can be larger than scroll dimension but the element can still be scrollable. We actually have to subtract borders from offset dimension to get the actual scrollable viewport of the element and compare that to scroll dimension.
For future reference
:scrollable jQuery selector filter is included in my .scrollintoview() jQuery plugin. Complete code can be found in my blog post if anybody needs it. Even though it didn't provide the actual solution Soumya's code considerably helped me solve the problem. It pointed me in the right direction.
I found this somewhere a couple of weeks ago. It worked for me.
var div = document.getElementById('container_div_id');
var hasHorizontalScrollbar = div.scrollWidth > div.clientWidth;
var hasVerticalScrollbar = div.scrollHeight > div.clientHeight;
/* you'll get true/false */
Try:
For vertical scroll bar
el.scrollHeight > el.clientHeight
For horizontal scrollbar
el.scrollWidth > el.clientWidth
I know this works for IE8 and Firefox 3.6+ at least.
This may seem (or be) a little hackish, but you could test the scrollTop and scrollLeft properties.
If they're greater than 0, you know there are scrollbars. If they're 0, then set them to 1, and test them again to see if you get a result of 1. Then set them back to 0.
Example: http://jsfiddle.net/MxpR6/1/
function hasScroll(el, direction) {
direction = (direction === 'vertical') ? 'scrollTop' : 'scrollLeft';
var result = !! el[direction];
if (!result) {
el[direction] = 1;
result = !!el[direction];
el[direction] = 0;
}
return result;
}
alert('vertical? ' + hasScroll(document.body, 'vertical'));
alert('horizontal? ' + hasScroll(document.body, 'horizontal'));
I believe there's a different property for IE, so I'll update in a minute with that.
EDIT: Appears as though IE may support this property. (I can't test IE right now.)
http://msdn.microsoft.com/en-us/library/ms534618(VS.85).aspx
Here is yet another solution:
As a few people pointed out, simply comparing offsetHeight and scrollHeight is not enough since they differ on elements with overflow hidden, etc., that still don't have scrollbars. So here I'm also checking if overflow is scroll or auto on the computed styles for the element:
var isScrollable = function(node) {
var overflowY = window.getComputedStyle(node)['overflow-y'];
var overflowX = window.getComputedStyle(node)['overflow-x'];
return {
vertical: (overflowY === 'scroll' || overflowY === 'auto') && node.scrollHeight > node.clientHeight,
horizontal: (overflowX === 'scroll' || overflowX === 'auto') && node.scrollWidth > node.clientWidth,
};
}
I maybe a little late to the party, but...
I believe you can detect for scrollbars with e.offsetWidth vs. e.clientWidth. Offset width includes borders and scrollbars, padding and width. Client width includes padding and width. Please see:
https://developer.mozilla.org/en/DOM/element.offsetWidth (second image)
https://developer.mozilla.org/en/DOM/element.clientWidth (second image)
You need to check:
Whether or not the element has overflow set to auto/scroll (including overflowX/Y) using the computed/cascaded/current style.
If the element does have overflow set to auto/scroll. Establish the offsetWidth and clientWidth.
If the clientWidth is less than the offsetWidth - right border (found again through the computed/cascaded/current style), then you know you have a scrollbar.
Do the same for the vertical (offset/clientHeight).
IE7 reports a clientHeight of 0 for some elements (I haven't checked why), therefore you always need the first overflow check.
Hope this helps!
There are several problems in case of checking the existence of scrollbars one of which is that in mac you don't have any visible scrollbar so both all the solutions above wouldn't give you an accurate answer.
So because the browser's rendering isn't very frequent you can check the having scroll with changing scroll and then setting it back:
const hasScrollBar = (element) => {
const {scrollTop} = element;
if(scrollTop > 0) {
return true;
}
element.scrollTop += 10;
if(scrollTop === element.scrollTop) {
return false;
}
// undoing the change
element.scrollTop = scrollTop;
return true;
};
For IE11 (Internet Explorer 11) I had to change the logic to:
// Subtract 3 (a small arbitrary number) to allow for IE reporting a difference of 1 when no scrollbar is present
var hasVerticalScrollbar = div.scrollHeight - 3 > div.clientHeight;
This is because IE reports scrollHeight as 1 larger than clientHeight when no scrollbar is present but approx 9 larger when a scrollbar is present
If you need to know if theres a scrollbar present for the whole webpage and with full browser support you can use this:
const hasScrollbar = document.body.scrollHeight > window.innerHeight
It's important to use window.innerHeight instead of document.body.clientHeight because in some mobile browsers clientHeight will not get the size of the address bar but scrollHeight will, so you get wrong calculations.
Is isn't for horizontal scrollbar it will be of height based calculation something like
element.offsetHeight - element.clientHeight
?
To conclude, for horizontal scrollbars, do height based calculation and for vertical scrollbars vice versa.
Just messing around here as none of the above solutions worked out for me (so far).
I have found some success with comparing a Div's scrollheight against its offsetHeight
var oh = $('#wrapDiv').get(0).offsetHeight;
var sh = $('#wrapDiv').get(0).scrollHeight;
It seems to give me an acurate comparison...so far. Does someone know if this is legitimate?
none of this answers are correct. you have to use this :
var div = document.getElementById('container_div_id');
var hasHorizontalScrollbar = (div.offsetWidth > div.clientWidth);
var hasVerticalScrollbar = (div.offsetHeight > div.clientHeight);

Is there a way to calculate how long it will take for a smooth scroll to end

I want my animation to run after the screen has stopped scrolling in Javascript, otherwise the user won't be able to see it. Unfortunately, the speed of scrolling in chrome can vary a lot, and I don't know how to calculate the speed.
Instead of calculating the scroll duration, why not just start the animation once you detect the page is in the right scroll location? You can use window.scrollY to get the current vertical scroll of the page, and element.offsetTop to get the top position of the element.
You can make a function to check if the element is visible on the page with something like the following code.
function elementInScrolledView(element) {
const pageTop = window.scrollY;
const pageBottom = pageTop + window.innerHeight;
const elementTop = element.offsetTop;
const elementBottom = elementTop + element.offsetHeight;
return ((elementBottom <= pageBottom) && (elementTop >= pageTop));
}
This code might need some edits if the element is taller than the window; you could compare just the tops of the elements?
You could start an interval checking each frame once the scrolling started until the function returned true, at which point you could clear the interval and start the animation.

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.

How to know whether a browser is displaying scrollbar is present or not in reactjs?

I am working on react project. when we make the screen size decrease from large to tiny, a scroll bar is appearing in the browser and as a result my testcases are failing.I wanted to know is there any way we can find whether a scroll bar is displayed in the browser for all types of screen sizes. Also is there any way to get the size of the scroll bar being displayed in the browser?
You can compare the height of your content with the height of the window.
So if (document.body.offsetHeight > window.innerHeight) then the scrollbar would be visible.
UPD:
Regarding scrollbar's sizes. Its width is just a difference between window.innerWidth and document.body.offsetWidth, and its height is equal to window.innerHeight.
So summing up:
let scrollbarSize = {
heigth: window.innerHeight,
width: window.innerWidth - document.body.offsetWidth
}
I would have preferred a comment but I do not have access to that yet.
I am assuming you are talking about height here if not please apply the same solutionwhere appropriate.
To know whether your browser is displaying the vertical scrollbar. Compare the height of the document and the screen height.
Method for the calculation of document height would usually vary across browsers in this case. Use something like this:
let scrollHeight = Math.max(
document.body.scrollHeight, document.documentElement.scrollHeight,
document.body.offsetHeight, document.documentElement.offsetHeight,
document.body.clientHeight, document.documentElement.clientHeight
);
To calculate your window height use:
const windowHeight = documentElement.clientHeight
If your scrollHeight is greater than the windowHeight then you can be most certain that the vertical scrollbar is present.
Therefore it would be easy to detect
In this sandbox I have tested two posible solutions. First approach (ScrollableComponent and hook useIsScrollable) is based on trying to scroll with element. If it does something then you know that it has scrollbar. The second aproach is based on measuring (ScrollableComponentA and hook useIsScrollableA). Measure wrapper element and inner element and compare its height and width.

Calculating Height of Sidebar Dynamically

I'm trying to work out the algorithm for a fixed div that grows in height (while scrolling) until it's equal to the height of the viewport or div with fixed position relative to another div and the bottom of the viewport
I am using Twitter Bootstrap affix to lock my secondary navigation bar (yellow) and my sidebar (black) to the top of the screen when the user scrolls that far. 
This works fine. The sidebar is the piece that's giving me trouble.  When it is in its in its starting position (as shown in the diagram belorw), I want the top of the bar to sit 30px
down from the secondary navigation bar (yellow) and 30px up from the bottom of the page. 
As the user scrolls, the bar should grow in height so that it remains 30px beneath the secondary navigation bar and 30px above the bottom of the screen (As shown in the diagram below)
After the bar is fixed position, I am able to do what I need to do.  
.sidebar { 
position:fixed;
top:100px;  
bottom:30px;
left:30px;
}
What I can't figure out is how to position the TOP of the sidebar relative to my
secondary navigation bar and the BOTTOM of my sidebar relative to the bottom
of the screen. I've tried calculating the height of the sidebar at the beginning and the end of the
scroll but this causes issues.
I've also tried calculating the final height of the sidebar and letting the bottom of
the sidebar just run off the edge of the screen (when it's in its initial position), but
if there's not enough content on the right side to warrant scrolling, I have no way
of getting to the bottom items in the scroll bar.  Plus my screen starts bouncing
in a really un­attractive way.
below is the current code in use:
ShelvesSideBar.prototype._resize_sidebar = function(_this) {
var PADDING = 50;
var window_height = $(window).height(),
nav_bar_height = $('.nav_bar').height() + $('.secondary_tabs').height(),
sidebar_height = window_height - nav_bar_height - PADDING,
sidebar_scrollable_height = sidebar_height - $('.bar_top').height();
_this.$container.height(sidebar_height);
_this.$container.find('.bar_bottom').height(sidebar_scrollable_height);
/* reset the nanoscroller */
_this.$container.nanoScroller();
};
   
this code is called on page load and again on window resize. Any help would be greatly appreciated!
I've been trying to do something similar (minus the fixed elements and navbars). What I found was in order to do any sort of relative height scaling every element above the element I wished to scale all the way up to the opening html tags had to have a relative height set, even if it was just height:100%;. (here's my original question Variable height, scrollable div, contents floating)
My goal was to have the body height fixed to window size like a native full screen application would be with my content subareas scrolling, so this is a bit off topic for what you're wanting to accomplish. But I tried using JS/JQ to start off with as you're trying to do currently and found that I simply couldn't get the window height because the default behaviour for height management is to expand the page height until everything on the page fits. And all the getHeight methods I tried we're getting the page height not window/viewport height as promised. So you may wish to try fixing your body's height to the window and going from there using overflow:scroll; to scroll the page.
A quick note on overflow:scroll; if you have users who use WP8 IE (and probably other versions of IE) it may be advantageous to implement FTscroller to handle all your scroll elements as the overflow property defaults to hidden and is a fixed browser property. The only problem with FTscroller is because it uses CSS offsets to move the content container it may wreak havoc on elements that are designed to switched to fix when they reach x height from top of page because technically the top of page (or rather the top of the container they're in) isn't at the top of the page anymore it's beyond it. Just something to be aware of if you do need to cater for this browser.
And apologies for the complexity of my sentence structure. :/
so I was able to figure this out, for anyone still looking. What I ended up doing was binding to the window scroll event and - whenever the scroll occurred - I check if the class "affix" has been added to the sidebar. If it has, then I perform one set of calculations to determine sidebar height. Otherwise, I perform the other set of calculations. Code below:
/* called on window scroll */
var PADDING = 70;
var window_height = $(window).height(),
nav_bar_height = $('.nav_bar').height() + $('.secondary_tabs').height(),
header_height = $('.prof_block').height() - nav_bar_height,
sidebar_height = _this.$container.hasClass("affix") ? window_height - nav_bar_height - PADDING : window_height - (header_height + nav_bar_height) - PADDING,
sidebar_scrollable_height = sidebar_height - $('.bar_top').height();
_this.$container.height(sidebar_height);
_this.$container.find('.bar_bottom').height(sidebar_scrollable_height);

Categories

Resources