Activating scrolling through Javascript

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>

Answer №1

If you wish to modify the variable ypos (user scroll position), you can do so by adjusting it like this:

var ypos = window.pageYOffset + Math.floor(height * 0.2);

The value of * 0.2 represents 20% of the height/window.innerHeight. This essentially adds a buffer of 20% of the height to the scroll position, allowing the remaining (opacity) code to load in advance.

You have the flexibility to change the value of 0.2 to control when the content appears on the screen while scrolling.

Answer №2

Incorporate JavaScript and verify the innerHeight property

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Optimizing load behavior in React using Node.js Express and SQL operations

As someone who is fairly new to programming, I have a question regarding the connection between server and client sides in applications like React and other JavaScript frameworks. Currently, I am working with a MySQL database where I expose a table as an ...

Send out Chrome Desktop notifications to reach all users

I recently integrated Chrome Desktop notifications into my website by following the steps outlined in this helpful guide: Chrome desktop notification example After adding the script code to my site, I was able to get it working smoothly. However, I encou ...

Tips for creating consistent background text size

i need assistance creating a box for text that looks like this https://i.stack.imgur.com/JOC0r.png my CSS code for the box is as follows: .bg-text-kol2 { background-color: #ffffff; background-size: 10px 10px; border-top-left-radius: 10px; border ...

Utilizing JavaScript and jQuery libraries in conjunction with periods

I am a bit puzzled about when to include the period before referencing class names. For instance, in this code snippet, why is a period included before the first use of the 'active-slide' class but not for the other two instances? var primary = ...

Is Jade used for making subsequent lines children of an included partial?

Recently, I've encountered an issue with a basic jade layout. Here is an example: include test.jade #bar hi In the test.jade file: #foo hello No matter what I try, the #bar element always ends up as a child of #foo. <div id="foo">hello &l ...

Having trouble sending values via POST request in Node.js using Express

Currently, I am in the process of learning how to use Express (v4) with Node.js. My main goal right now is to create a basic REST API. This API specifically focuses on one endpoint: /orders. The main functionality I am trying to achieve is the ability to r ...

Achieve seamless alignment of radio group labels alongside radio buttons through the use of only CSS

After using a table to display radio buttons with labels in the past, I am now attempting to achieve the same result using only CSS. Is there a CSS technique that will allow me to position the label text neatly on top of the corresponding radio button? He ...

Revamping array elements in React

Once I added an element to the array, I needed to update this array by doubling all elements except for the one that was just added. Despite trying setArray([]) before retrieving the array from the database, it didn't seem to work... const [array, se ...

What is the process for deleting certain code from a main component within a React webpage without altering the main component itself?

I have a main component named Layout.jsx that includes the essential elements for the website such as the navigation bar and meta tags. It also contains a Google tag to track analytics across the entire site. Now, I have a specific webpage for Google Ads w ...

When using Node.js, Express.js, and MongoDB, ensure that the route.post() function is provided with proper callback functions instead of

I've been working on setting up a MEAN (MongoDB, Express, Node.js, Angular 6) application. I'm trying to post user signup form data to a MongoDB database, but I keep getting an error message. This is my first time working with the MEAN stack and ...

Clicking the identical button on multiple overlapping elements using Selenium and Node.js

Working with Selenium has presented a challenge when trying to close multiple HTML elements that share the same "close" button and overlap each other. The initial approach of looping through them individually to close seemed unsuccessful. The first step i ...

Tips for expanding a text input field vertically, not horizontally like in Facebook, while typing or by holding down the Shift key and pressing Enter

I've come across numerous plugins that enable vertical resizing of a textarea and others that allow horizontal resizing of an input field. However, I have yet to find one that enables vertical resizing of an input field similar to Facebook's comm ...

Enhance your website with a stylish drop-down menu from inc.com

I am trying to create a drop and hide menu effect similar to the one on Here is my current demo: http://jsfiddle.net/elementhttp/56ThC/ $("#1").mouseover(function(){ //alert("aaaaaaaaaa"); just for testing $(".block2").stop().fadeToggle(700 ...

How can I line up the bootstrap datepicker with a bootstrap column?

I currently have Bootstrap 3.3.7 and a bootstrap datepicker version 1.6.4 integrated into my project. However, I am facing an issue where the datepicker does not fill up the designated column within a div with the class col-md-6. Here is the HTML code sni ...

Modify the properties of the following bdi element that contains text using JQuery

I am not a tech expert, but I have created a script and am running it on a website using Tampermonkey. Website code:- <div id="__grid1-wrapperfor-__label44" class="sapUiRespGridSpanL1 sapUiRespGridSpanM3 sapUiRespGridSpanS6 sapUiRespGridS ...

Receiving the most recent data in a protractor examination as a text string

My goal is to fetch an input value for a specific operation in protractor. I am attempting to make an ajax request using protractor and need to assign a unique value (referred to as groupCode) to a JSON object that will be sent to the server. Initially, I ...

Detecting the State of the Keyboard in Ionic 2

Seeking an easy way to determine if the mobile device keyboard has been opened or closed using Ionic2 and Angular2. Is there a 'keyboard-open' or 'keyboard-close' class that Ionic sends to the body/html? ...

Connecting a controller to a directive in AngularJS: A step-by-step guide

Imagine a scenario with the following HTML structure: <div ng-app="testApp"> <div ng-controller="controller1"> {{controller1}} </div> <div ng-controller="controller2"> {{controller2}} </div> ...

What is the best way to access and iterate through JSON data?

I am trying to extract data from my Json file, however, I cannot use a specific 'key' because it changes on a daily basis. https://i.sstatic.net/sZySk.png My attempted solution is as follows: template: function(params) { const objects ...

How to shift an image to the right side of the navbar

Is it possible to change the position of an image within a navbar from left to right? I have tried using the float property but it doesn't seem to work. .logo-img{ float: right; margin: 0px 15px 15px 0px; } <a class="navbar-brand logo-img" ...