A friend of mine created a web page to help me learn some JavaScript. He designed a feature where the content in each div becomes visible as soon as the user scrolls past it. However, I noticed that the content appears too late for my liking. I would like to modify it so that the animation activates when the user has scrolled 80% down the section above it or -20% into the next section. I apologize for the lengthy explanation, but it's quite challenging to explain in words. Please check out the jsfiddle link provided to see what I mean.
Here is the fiddle
<script>
function scrollContent(){
//store the header as a variable
var header = document.getElementById("header");
//IMPORTANT NOTE ABOUT ARRAYS:
//the first item in an array isnt the "1"st itemm its the "0"th.
//so to select the first item, you say sections[0], to select the second item, you say sections[1] etc etc.
//get all of the elements with the class "section"
//and store them in an array
var sections = document.getElementsByClassName("section");
//do the same as above, for the "content" elements.
var contents = document.getElementsByClassName("content");
//get the height of the page
//which, because of our css, is also the height of one section
var height = window.innerHeight;
//get users position on the page
var ypos = window.pageYOffset;
//which section the user is currently on
//we work this out by dividng the user's position on the page
//by the height of the actual page (which is the same height as one section)
//for example, if the user is 1000 pixels down and the page is 500 pixels high,
//1000 divided by 500 is 2, so they are on the second section.
//we wrap the sum in Math.floor() to round it down to the nearest whole number
var currentSection = Math.floor(ypos / height);
//stops the animation breaking when people try to scroll above the top of the page
if(currentSection < 0){
currentSection = 0;
}
//loop through all of the sections
for(var i = 0; i < sections.length; i++){
//if the section is currently in view
if(i <= currentSection){
//make the content viewable
contents[i].style.opacity = "1";
//if not
} else {
//hide the content
contents[i].style.opacity = "0";
}
}
}
window.addEventListener("scroll", scrollContent);
scrollContent();
</script>