Answer the question
In order to leave comments, you need to log in
How to determine browser height from body and html?
Good afternoon!
I added to the site a change in the background color at a certain percentage of the scroll in height. The code:
function scrollfunction() {
var body = document.body;
if(body.scrollTop / body.scrollHeight < 0.07) {
body.className = "white";
} else {
if(body.scrollTop / body.scrollHeight < 0.20) {
body.className = "red";
} else {
if(body.scrollTop / body.scrollHeight < 0.30) {
body.className = "violet";
} else {
if(body.scrollTop / body.scrollHeight < 0.45) {
body.className = "blue";
} else {
if(body.scrollTop / body.scrollHeight < 0.60) {
body.className = "green";
} else {
if(body.scrollTop / body.scrollHeight < 0.75) {
body.className = "orange";
} else {
if(body.scrollTop / body.scrollHeight < 0.96) {
body.className = "asphalt";
} }}}}}}
}
Answer the question
In order to leave comments, you need to log in
It 's written here. There is nothing special to add =)
And I would change the code a little:
1. It is not necessary to calculate the share in each check, it is better to save it in a variable and operate on it already.
2. It will be more readable if you use else if
/**
* Определяет позицию скролла по отношению к высоте полоски скролла.
* @return {Number}
*/
function getScrollPosition() {
var scrollHeight = document.documentElement.scrollHeight;
var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
return Math.round(scrollTop/scrollHeight);
};
function scrollfunction() {
var body = document.body;
var scrollPosition = getScrollPosition();
if (scrollPosition < 0.07) {
body.className = "white";
} else if (scrollPosition < 0.20) {
body.className = "red";
} else if (scrollPosition < 0.30) {
body.className = "violet";
} else if (scrollPosition < 0.45) {
body.className = "blue";
} else if (scrollPosition < 0.60) {
body.className = "green";
} else if (scrollPosition < 0.75) {
body.className = "orange";
} else if (scrollPosition < 0.96) {
body.className = "asphalt";
};
};
in modern browsers, the viewport can be measured by window.innerHeight.
but it might be useful
document.documentElement.[scrollHeight,clientHeight,offsetHeight]
document.body.[scrollHeight,clientHeight,offsetHeight]
window.[inner,outer][Height,Width]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question