How to set the scroll height dynamically?
You can handle window.onscroll
, prevent the event from propagating if the user has scrolled too far and send them back to where they're meant to be looking:
window.onscroll = function (e) {
var maxViewableHeight = 1400;
if (document.body.scrollTop + window.innerHeight > maxViewableHeight) {
console.log(document.body.scrollTop + window.innerHeight);
e.preventDefault;
document.body.scrollTop = maxViewableHeight - window.innerHeight;
return false;
}
}
Update
Here is a more cross-browser friendly version, tested in Chrome 25, Firefox 19, IE10/IE9, Safari 5, Opera 12. In IE, Safari and Opera it bounces a bit. Particularly Opera due to its fancy smooth scrolling, makes me appreciate Firefox more because it has smooth scrolling and was perfect.
window.onscroll = function (e) {
var maxViewableHeight = 1400,
scrollTop = getScrollTop();
if (scrollTop + window.innerHeight > maxViewableHeight) {
e.preventDefault();
window.scrollTo(0, maxViewableHeight - window.innerHeight);
return false;
}
}
function getScrollTop() {
if (typeof window.pageYOffset !== 'undefined') {
return window.pageYOffset;
}
var body = document.body,
docElement = document.documentElement;
docElement = (docElement.clientHeight) ? docElement : body;
return docElement.scrollTop;
}
Chris
Updated on June 04, 2022Comments
-
Chris almost 2 years
I have a div which has a height of 1200px and a width of the browser window. Just below that div I have another div with a height of 1000px. Now at the moment when scrolling down you will be able to scroll until the end of the second div. What I would like is to set the scroll height, so for example I would like to say you should only be able to scroll for 1200px. That way my second div would not be visible to the visitor. Is there some way to achieve this with JQuery?
I uploaded a picture emphasizing my problem:
-
Chris about 11 yearsAny idea why this does neither seem to work in IE nor in Firefox?
-
Chris about 11 yearsPerfect, thank you alot for your efforts! Changing the size of the scrollbar is probably not possible, is it? So that the user doesn't see that the page is actually still longer.
-
Daniel Imms about 11 yearsNo you can't change the size of the scrollbar. However that would basically achieve the same effect as placing the "hidden stuff" in a
<div>
and hiding that<div>
with JavaScript.