What is the best method to determine when 20% of a "<section>" element is within the user's view?

Looking at the layout, I have two sections that take up the entire page. My goal is to detect when the second section is 20% visible while scrolling, and then smoothly scroll to lock that section in place so it occupies the full space. This action should also apply to any additional sections that are added in the future.

(I am able to handle the smooth scrolling part myself).

Does anyone have any ideas on how I can achieve this functionality?

* {
    margin: 0;
    padding: 0;
}

#s1 {
  height: 100vh;
  background: red;
}

#s2 {
  height: 100vh;
  background: blue;
}
<section id="s1"></section>
<section id="s2"></section>

Answer №1

let mainSection = document.querySelector('section'),
    sectionHeight = mainSection.offsetHeight,
    lastScrollPosition = 0;
document.addEventListener("scroll", function() {
    let scrollPosition = window.pageYOffset || document.documentElement.scrollTop;

    if (scrollPosition > lastScrollPosition) { //on scroll down
        if (scrollPosition >= sectionHeight * 0.2 && scrollPosition < sectionHeight) { //if 20% of section2 is visible
            window.scrollTo(0, sectionHeight * 1); //scroll to section2
        } else if (scrollPosition >= sectionHeight * 1.2 && scrollPosition < 2 * sectionHeight) { //if 20% of section3 is visible
            window.scrollTo(0, sectionHeight * 2); //scroll to section3
        } else if (scrollPosition >= sectionHeight * 2.2) { //if 20% of section4 is visible
            window.scrollTo(0, sectionHeight * 3); //scroll to section4
        }
    }
    lastScrollPosition = scrollPosition <= 0 ? 0 : scrollPosition;
});
* {
    margin: 0;
    padding: 0;
}
html,body{
  scroll-behavior: smooth;
}
section{
  height: 100vh;
}
#s1 {
  background: red;
}
#s2 {
  background: blue;
}
#s3{
  background: yellow;
}
#s4{
  background:purple;
}
<section id="s1"></section>
<section id="s2"></section>
<section id="s3"></section>
<section id="s4"></section>

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

Encountering an issue while trying to utilize the firestorePlugin from vuefire in Vuejs 3 createApp. The problem is that I am receiving an Uncaught TypeError: Cannot set property '$

I recently encountered an issue in my Vue.js 3 app with the following code snippet in my main.js file: import { createApp } from "vue"; import App from "./App.vue"; import { firestorePlugin } from "vuefire"; const app = creat ...

What are the steps to configure ESlint and Prettier with the Airbnb style guide for a React Native/JavaScript project (Expo) in VS Code?

I have looked through numerous tutorials on this topic, but I haven't been able to get it to work. In the tutorials, when you run npm install eslint, it usually prompts you in the command line about using a popular style guide. However, this no longer ...

Is it possible to make the li elements within my ul list display on multiple lines to be more responsive?

My credit card icons are contained within a ul. I have used the properties background-image and display:inline for the LIs, which display nicely on larger screens. Unfortunately, when viewed on mobile devices, the icons are cut off. My question is whether ...

Utilize a standard PHP script for every subdirectory within a domain

I'm currently working on a website and the design I'm using involves changing the URL in the address bar using the history API when the page content changes through JavaScript and AJAX. However, I also want each "page" of the website to be access ...

Press on the row using jQuery

Instead of using link-button in grid-view to display a popup, I modified the code so that when a user clicks on a row, the popup appears. However, after making this change, nothing happens when I click on a row. Any solutions? $(function () { $('[ ...

A JavaScript function that produces an array as an output

Could anyone explain why the output vector from the function TriangulosParaLinhas is not being stored in the vector Lines? if (lineMode == true) { var lines = triangulosParaLinhas(vertices); } function triangulosParaLinhas(vertices) { var poi ...

In the XHTML mode, MathOverflow's invaluable mathematical expertise shines brightly

I am interested in incorporating the unique “piece of valuable flair™” from MathOverflow onto my website. The issue I am facing is that I want my webpage to comply with XHTML5 standards, meaning it should be served with the MIME type application/xht ...

Problem with loading image from local path in Angular 7

I'm having trouble loading images from a local path in my project. The images are not rendering, but they do load from the internet. Can someone please help me figure out how to load images from a local path? I have already created a folder for the im ...

What is the process for embedding HTML and CSS content into an Outlook email?

Has anyone experienced trouble adding an HTML and CSS web page to an Outlook email? I attempted to use the "Insert as text" option, but the CSS file is not loading correctly in Outlook. Any suggestions on how to fix this? The error message states that the ...

Steps to establish a connection with a remote MYSQL database using the actual IP address in Node.js

In my Nodejs file, I have set up the connection as follows. The issue arises when attempting to connect to the remote database on a server. module.exports = { host: '234.32432.32432',//this is an example IP address and not a real one. use ...

What is the best method for creating an HTML table using a Javascript function in PHP?

When working with a PHP file to generate a table based on SQL query results, I encountered an issue where only one incorrect row is returned. If anyone has a basic idea of what might be happening, it would be greatly appreciated. This is my HTML Code: &l ...

Submitting HTML form data to a Java class via JavaScript, following validation with JavaScript within a JSP file

I am struggling with posting data obtained from an html form created in a jsp file using javascript and sending it to a java class after validating the form data. I was exploring alternatives to Ajax since I am not well-versed with those tools, but if you ...

Retrieving the output of an asynchronous function within another function in JavaScript

I'm facing an issue with the Chrome API functions being asynchronous, making it difficult for me to get their return value. Here's a snippet of code that demonstrates my problem. I'm working with AngularJS. $scope.storageGet = function( ...

Implementing a validator based on the operator selection in react-querybuilder

Is it possible to add validators to fields that are only active when using the like operator? For example, if the like or unlike operators are used in the phoneNumber field without the % sign, it should be invalid. If the = operator is used, the % sign sho ...

How can CSS Bootstrap flex width be used to prevent parent element from expanding too much with long, single line text? Utilizing ell

​Having encountered a tricky situation with CSS and flexbox, I found myself needing to implement the following properties: ​text-overflow: ellipsis; ​white-space: nowrap; ​overflow: hidden; However, when the text was too long, it caused t ...

What is the reason for using a string as the index of an array in the following code?

var arrayOfNumbers = [1, 2, 3, 4, 5, 6, 78]; for(var index in arrayOfNumbers){ console.log(index+1); } The result produced by the given code snippet is as follows: 01 11 21 31 41 51 61 What is the reason behind JavaScript treating these ...

Displaying data in an HTML table using PHP and adding a popup

I've successfully created a PHP script that retrieves data from a MySQL database and organizes the results into an HTML table. Within one of the fields in the database, there are links to file(s), separated by commas. Everything is working well thanks ...

Can access parent refs when exporting a child component with withStyles by following these steps:

For example: Child Component Code // Assume there is a styles object 's' being used in this component class Child extends Component { render() { return ( <h1 ref={(ref)=>{this.ref = ref}}>Hello</h1> ); } } export defau ...

Guide on implementing a template within a form using Vue.js

I have set up a Vue instance for handling the form data var formInstance = new Vue({ el: '#amount_form', data: { logdate: '', amount:'', description:'' }, methods: { ...

Remove any nulls or undefined values from the object

I have developed a custom function that eliminates null and undefined values from an object. However, it seems to be mistakenly removing keys where the value is 0 as well. For instance: { key1: 'value1', key2: 0 } Even though it shouldn&ap ...