How to scroll to show a part of a webpage - javascript

What are the different ways you can control/read the Scrollbar in a web browser with JavaScript, apart from anchors? -- Unless you can dynamically create anchors and tell the browser to scroll down to that.

To scroll by an arbitrary amount:
//Parameters being the amount by which to scroll in pixels (horizontal and vertical)
window.scrollBy(50, 50);
To scroll to a certain point:
window.scrollTo(0, 30);
To read current position:
document.body.scrollLeft
document.body.scrollTop

Here is one example of how you can control X/Y scrolling without anchors. ( ScrollX/ScrollY)
The key part I suppose is the following
function saveScrollCoordinates() {
document.Form1.scrollx.value = (document.all)?document.body.scrollLeft:window.pageXOffset;
document.Form1.scrolly.value = (document.all)?document.body.scrollTop:window.pageYOffset;
}

Using the scrollTop property (inherent of all elements) you can scroll to a specific pixel height. So, scrolling to the height of a specific anchor would involve querying for the offset of that anchor and setting scrollTop accordingly. Just for illustration's sake; this is how you would scroll to a specified element with jQuery:
var top = $('div#something').offset().top;
$(document).scrollTop(top);
NOTE: jQuery's implementation can be misleading; it accepts document but the top-most element with the scrollTop property is, in fact, document.documentElement (usually refers to <HTML>).
There is also a scrollLeft property for horizontal scrolling.
And of course, you can read these properties:
var currentScrollTop = document.documentElement.scrollTop;

Prototype implements a scrollTo() function that makes it really easy to scroll to a particular element:
$("#elementID").scrollTo();
The implementation internally calls window.scrollTo to do the actual scrolling.

var coord = {top:null,left:null,width:null,height:null};
if (typeof window.pageYOffset == 'number') {
coord.top = window.pageYOffset; coord.left = window.pageXOffset;
} else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
coord.top = document.body.scrollTop; coord.left = document.body.scrollLeft;
} else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
coord.top = document.documentElement.scrollTop; coord.left = document.documentElement.scrollLeft;
}
if (typeof window.innerWidth == 'number') {
coord.width = window.innerWidth; coord.height = window.innerHeight;
} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
coord.width = document.documentElement.clientWidth; coord.height = document.documentElement.clienthHeight;
} else if(document.body && (document.body.clientWidth || document.body.clientHeight)) {
coord.width = document.body.clientWidth;
coord.height = document.body.clientHeight;
}

Related

Check if the scroll is currently at the bottom - no jQuery

What is the easiest way to check if the window scroll is at the bottom—without using jQuery?
I've come across some methods, but most of them don't work cross browser.
Here is one technique that works across a handful of browsers I tested
window.onscroll = function () {
var totalHeight = document.documentElement.scrollHeight;
var clientHeight = document.documentElement.clientHeight;
var scrollTop = (document.body && document.body.scrollTop)
? document.body.scrollTop : document.documentElement.scrollTop;
if (totalHeight == scrollTop + clientHeight)
console.log('Bottom');
}

Javascript Scroll Height Percentage Math

I have a simple JS module that calculates the percentage of the current scroll position.
var scrollPercent = (function() {
"use strict";
var module = {
config: {
},
init: function() {
return this.percent();
},
percent: function() {
var windowHeight = this.getWindowHeight();
var docHeight = this.getDocHeight();
var scrollPosition = this.getScrollPosition();
var result = ((scrollPosition + windowHeight) / docHeight) * 100;
return Math.floor(result);
},
getScrollPosition: function() {
return (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
},
getWindowHeight: function() {
return window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight || 0;
},
getDocHeight: function() {
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
);
}
};
return module;
});
var scroller = new scrollPercent;
window.onscroll = function(event) {
console.log(scroller.init());
};
This is working as expected, if the window height is 500px and the doc height is 1000px, then the initial scroll position is 50%. If you were to scroll to the bottom it would be 100%.
What I would like to do is have my initial value be 1% and when scrolling to the bottom it return 100% (like it is now).
The problem is that my initial value of 50% is based off the window height (half the page is showing). For some reason I can't figure out the necessary math to have it start at 1% and go to 100% when reaching the bottom.
So, after a bunch of fiddling I came across your solution...
You have to take into consideration the current position of the document and the scroll bar. So if you want to get it between 0-100 you have to exclude the height of the window in your docHeight.
In your function I created a variable called initDiff and basically used this to calculate your value between 0-100.
This is how I set up your init function. Notice docHeight. Also, notice initDiff which calculates a difference that needs to be subtracted from your result. I don't use any scroll positioning because the initDiff is calculated for when the scroll-bar positioning is 0
init: function() {
var windowHeight = this.getWindowHeight();
var docHeight = this.getDocHeight() - windowHeight;
initDiff = (windowHeight / docHeight) * 100;
console.log('Difference : ' + initDiff);
return this.percent();
}
Below is your percent function that I changed up a bit. Again, docHeight takes into consideration the current height of the window. Your result, once you take out the windowHeight from docHeight your number generally ranged from something like 50-150, it all depends on the window height. What I do is "keep" that number, but I calculate that difference. So for that range, your initDiff will be 50. If the range was 56-156 your initDiff will be 56
percent: function() {
var windowHeight = this.getWindowHeight();
var docHeight = this.getDocHeight() - windowHeight;
var scrollPosition = this.getScrollPosition();
var result = ((scrollPosition + windowHeight) / docHeight) * 100 - initDiff;
console.log('Window Height : ' + windowHeight);
console.log('Document Height : ' + docHeight);
console.log('Scroll Position : ' + scrollPosition);
return Math.floor(result);
}
Here is the fiddle : http://jsfiddle.net/XNVNj/2/
Just look at your console. Should explain it all.

Animate element on scroll

I would like to animate a div when user scrolls the page.
For that, i implemented this code:
var slide = jQuery(".apresentacao-spc-01");
var opening = false;
var closing = false;
var pos = jQuery(window).scrollTop();
jQuery(window).scroll(function() {
var pos = jQuery(window).scrollTop();
console.log(pos);
if (pos > 100) {
if (!opening) {
opening = true; closing = false;
slide.stop().animate({
'opacity': 1,
'margin-left': '0px'
}, 700, function() {
opening = false;
});
}
} else {
if (!closing) {
closing = true; opening = false;
slide.stop().animate({
'opacity': 0,
'margin-left': '-1000px'
}, 500, function() {
closing = false;
});
}
}
});
The issue is:
Using "if (pos > 100) {", if the user resolution is big enough to show the element before he needs to scroll, he won't see the element unless he begins to scroll the page.
My question is:
How can I get a scroll animation that will be executed when the element is visible?
I mean: If the element is visible on page load, the animation automatically starts... If the element is not visible on page load, the animation waits the scroll reach the element to start...
Thanks.
There a few different things you could do. My first thought was to query the height of the viewport with something like this:
var viewportWidth = document.documentElement.clientWidth
, viewportHeight = document.documentElement.clientHeight
And then trigger the animation if it is taller than the distance the element is down.
A more dynamic solution would be to use a function that checks to see if the element is in viewport the automatically, that way you wouldn't need to worry about adjusting the height if you changed stuff on your page:
function isElementInViewport (el) {
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
);
}
credit to this response.
There is a use guide and further information in the link provided.
Good luck!

finding the maximum scroll position of a page

I have made the body of the page 200% tall so that it fits on a screen twice. Using javascript I am making it keep scrolling to the top or bottom when you scroll. For this, I need to find out the lowest scroll point of the page on any browser or screen size so that it stops when it gets there.
No JQuery please.
Thank you.
My code: (it is still being put together so needs a bit of work)
function getScrollXY() {
var x = 0, y = 0;
if( typeof( window.pageYOffset ) == 'number' ) {
// Netscape
x = window.pageXOffset;
y = window.pageYOffset;
} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
// DOM
x = document.body.scrollLeft;
y = document.body.scrollTop;
} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
// IE6 standards compliant mode
x = document.documentElement.scrollLeft;
y = document.documentElement.scrollTop;
}
return [x, y];
}
function scrollup() {
if (xy[1] > 0) {
window.scrollBy(0,-100);
setTimeout(scrollup,200);
} else {
null;
}
}
function scrolldown() {
if (xy[1] < ) {
window.scrollBy(0,100);
setTimeout(scrolldown,200);
} else {
null;
}
}
function dothescroll() {
var xy = getScrollXY();
var y = xy[1];
setTimeout(function(){
if (xy[1] > y) {
scrollup();
} else {
scrolldown();
}
},200);
}
This is the cross browser compatible version:
var limit = Math.max( document.body.scrollHeight, document.body.offsetHeight,
document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight );
While this is not part of any specification, you could try window.scrollMaxY.
Returns the maximum number of pixels that the document can be scrolled vertically.
https://developer.mozilla.org/docs/Web/API/Window/scrollMaxY
Fallback if unavailable:
var scrollMaxY = window.scrollMaxY || (document.documentElement.scrollHeight - document.documentElement.clientHeight)
Note, documentElement isn't always the scrolling element (some browsers use body instead). The solution is the new scrollingElement property, which returns a reference to the Element that scrolls the document. It is specified, but still a working draft.
var limit = document.body.offsetHeight - window.innerHeight;
// document.body.offsetHeight = computed height of the <body>
// window.innerHeight = available vertical space in the window
Compare xy[1] < limit
Note: You might need to increase the value by margin and/or padding of the body. You can also try using clientHeight instead of offsetHeight.
My solution based on the solutions above and what I use in 2022.
AKA scrollMaxY
const scrollMaxValue = () => {
const body = document.body;
const html = document.documentElement;
const documentHeight = Math.max(
body.scrollHeight,
body.offsetHeight,
html.clientHeight,
html.scrollHeight,
html.offsetHeight
);
const windowHeight = window.innerHeight;
return documentHeight - windowHeight;
};
scrollMaxValue()
window.scrollTo(0, document.body.scrollHeight);
this will work..

JavaScript get window X/Y position for scroll

I'm hoping to find a way to get the current viewable window's position (relative to the total page width/height) so I can use it to force a scroll from one section to another. However, there seems to be a tremendous amount of options when it comes to guessing which object holds the true X/Y for your browser.
Which of these do I need to make sure IE 6+, FF 2+, and Chrome/Safari work?
window.innerWidth
window.innerHeight
window.pageXOffset
window.pageYOffset
document.documentElement.clientWidth
document.documentElement.clientHeight
document.documentElement.scrollLeft
document.documentElement.scrollTop
document.body.clientWidth
document.body.clientHeight
document.body.scrollLeft
document.body.scrollTop
And are there any others? Once I know where the window is I can set an event chain that will slowly call window.scrollBy(x,y); until it reaches my desired point.
The method jQuery (v1.10) uses to find this is:
var doc = document.documentElement;
var left = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0);
var top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
That is:
It tests for window.pageXOffset first and uses that if it exists.
Otherwise, it uses document.documentElement.scrollLeft.
It then subtracts document.documentElement.clientLeft if it exists.
The subtraction of document.documentElement.clientLeft / Top only appears to be required to correct for situations where you have applied a border (not padding or margin, but actual border) to the root element, and at that, possibly only in certain browsers.
Maybe more simple;
var top = window.pageYOffset || document.documentElement.scrollTop,
left = window.pageXOffset || document.documentElement.scrollLeft;
Credits: so.dom.js#L492
Using pure javascript you can use Window.scrollX and Window.scrollY
window.addEventListener("scroll", function(event) {
var top = this.scrollY,
left =this.scrollX;
}, false);
Notes
The pageXOffset property is an alias for the scrollX property, and The
pageYOffset property is an alias for the scrollY property:
window.pageXOffset == window.scrollX; // always true
window.pageYOffset == window.scrollY; // always true
Here is a quick demo
window.addEventListener("scroll", function(event) {
var top = this.scrollY,
left = this.scrollX;
var horizontalScroll = document.querySelector(".horizontalScroll"),
verticalScroll = document.querySelector(".verticalScroll");
horizontalScroll.innerHTML = "Scroll X: " + left + "px";
verticalScroll.innerHTML = "Scroll Y: " + top + "px";
}, false);
*{box-sizing: border-box}
:root{height: 200vh;width: 200vw}
.wrapper{
position: fixed;
top:20px;
left:0px;
width:320px;
background: black;
color: green;
height: 64px;
}
.wrapper div{
display: inline;
width: 50%;
float: left;
text-align: center;
line-height: 64px
}
.horizontalScroll{color: orange}
<div class=wrapper>
<div class=horizontalScroll>Scroll (x,y) to </div>
<div class=verticalScroll>see me in action</div>
</div>
Maybe this has not been mentioned due to this article been 11 years old.
But currently I am using window.scrollY (inside an onscroll event listner and a throttle function) and it works just fine most of the time.
And when it doesn't I use intersectionObserver API for similar effect which is also a fairly new feature I guess.
if (window.scrollY > desiredAmount) {
doThis();
}
function FastScrollUp()
{
window.scroll(0,0)
};
function FastScrollDown()
{
$i = document.documentElement.scrollHeight ;
window.scroll(0,$i)
};
var step = 20;
var h,t;
var y = 0;
function SmoothScrollUp()
{
h = document.documentElement.scrollHeight;
y += step;
window.scrollBy(0, -step)
if(y >= h )
{clearTimeout(t); y = 0; return;}
t = setTimeout(function(){SmoothScrollUp()},20);
};
function SmoothScrollDown()
{
h = document.documentElement.scrollHeight;
y += step;
window.scrollBy(0, step)
if(y >= h )
{clearTimeout(t); y = 0; return;}
t = setTimeout(function(){SmoothScrollDown()},20);
}

Categories

Resources