Switch classes according to scrolling levels

My webpage consists of multiple sections, each occupying the full height and width of the screen and containing an image.

As visitors scroll through the page, the image in the current section comes into view while the image in the previous section disappears. This creates a visually appealing effect as users navigate through the content.

If you'd like to see this concept in action, check out this live example:

Here is an example of how I achieve this effect with my code. When a user is on an active section, the "active" class is applied to the corresponding "article" tag. As the user moves to a different section, the "active" class is removed from the previous section and added to the new one.

.section .image {
   opacity: 0;
}

.section .active .image {
    opacity: 1;
}
    <section class="all-sections-wrap">

    <article class="section">

    <div class="image">
    <img src="blabla.png">
    </div>

    </article>

    <article class="section">

    <div class="image">
    <img src="blabla.png">
    </div>

    </article>

    <article class="section">

    <div class="image">
    <img src="blabla.png">
    </div>

    </article>

    <section>

Although I have researched extensively on stackoverflow, I have been unable to find a suitable script for accurately detecting offsets and page heights. Any assistance with this issue would be greatly appreciated.

Thank you!

Answer №1

Utilize the .scroll() method on the window element to detect when the page has been scrolled. This allows you to determine the number of pixels the page has been scrolled using $(window).scrollTop(). Next, compare this value to the offset of the specific element where you want to apply the class by utilizing $("#element").offset().top

$(window).scroll(function(){
    if($(window).scrollTop() >= $("#element").offset().top + $("#element").height() || $(window).scrollTop() < $("#element").offset().top)
        $('#element').removeClass('active');
    else
        $('#element').addClass('active');
});

If you have multiple sections and want to avoid duplicating the code, consider using each(). However, be cautious as testing each section every time scroll() is triggered could potentially impact performance.

$(window).scroll(function(){

    $('.section').each(function() {
        if($(window).scrollTop() >= $(this).offset().top + $(this).height() || $(window).scrollTop() < $(this).offset().top)
            $(this).removeClass('active');
        else
            $(this).addClass('active');
    });

});

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

Toggle button to create a fade in/out effect

Below is the HTML code snippet: <html> <head> <Script type = "text/javascript" src = "CprMdlrSrch.js"></Script> <link type="text/css"rel="stylesheet"href="CprMdlrSrch.css"/> </head> <body> <div id=" ...

Can the JavaScript code be altered within the client's browser?

So, I'm using JQuery Validator on my webform to validate form data. However, I haven't added any validation on the server side. I'm curious if it's possible for a user to modify the code and bypass my validations in their browser. If th ...

The background widths do not stretch to 100%, but rather stop right before reaching the

Experience it live: Adjust your screen width slightly to activate the mobile layout, but ensure that there is still enough room for a horizontal scroll bar. Astonishingly, all my background images stop short of this point. Innovative Fix To prevent the ...

Tips for effectively managing loading and partial states during the execution of a GraphQL query with ApolloClient

I am currently developing a backend application that collects data from GraphQL endpoints using ApolloClient: const client = new ApolloClient({ uri: uri, link: new HttpLink({ uri: uri, fetch }), cache: new InMemoryCache({ addTypename: f ...

React Bootstrap always displays tooltips

I have integrated react-bootstrap into my project. I am currently attempting to keep a tooltip always displayed, but I am facing some challenges in achieving this. Below are the approaches I have tried so far: <Card style={{width: '10rem'}} ...

Having trouble with fs.readFile in Node.JS on Ubuntu?

Currently, I am facing an issue when trying to read XML files. Strangely, the code works flawlessly on my personal computer running OS X. However, when I run the same code on a DigitalOcean Ubuntu 16 Server, it fails to produce any results. I am utilizing ...

Exploring deep within JSON data using jQuery or Javascript

I have a substantial JSON file with nested data that I utilize to populate a treeview. My goal is to search through this treeview's data using text input and retrieve all matching nodes along with their parent nodes to maintain the structure of the tr ...

When using Javascript, an error is being thrown when attempting to select a nested element, stating that it is not a function

I am facing a challenge in selecting an element within another element, specifically a button within a form. Typically, I would use jQuery to achieve this as shown below: element = $('#webform-client-form-1812 input[name="op"]'); However, due t ...

Google Chrome Content Script: Unable to Trigger Dynamically Added Button

In my project, the custom Google Chrome Extension content script is designed to receive a message from popup.html through the Google Chrome Message Passing API once a user logs in using popup.html. This content script is responsible for dynamically adding ...

Passing multiple parameters in URL for APIs using Next.js

Is there a way to pass multiple parameters and retrieve results from the next.js API? I found the documentation very helpful, you can check it out here /api/posts/[postId].js The above setup works fine, but I want to know if it's possible to pass an ...

The Jquery .clone() function presents issues in Internet Explorer and Chrome browsers, failing to perform as expected

I need to duplicate an HTML control and then add it to another control. Here is the code I have written: ko.bindingHandlers.multiFileUpload = { init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { va ...

Issue with Kendo dropdown's optionLabel functionality malfunctioning

Check out the Kendo code snippet below for a dropdown control. I'm currently facing an issue where I am trying to display a "Please select" option in the dropdown. This code works perfectly fine for all other dropdowns except for this specific one. T ...

Auto-collapse sidebar upon clicking anywhere on the page

I have a dynamic sidebar that appears when the user clicks on a hamburger button. Here is the layout: $('#nav-toggle').click(function() { if($('#nav-toggle').hasClass('active')){ $('.menu').animate({ r ...

Accessing content from a text file and showcasing a designated line

Apologies if my wording was unclear... In this scenario, we will refer to the text file as example.txt. The value in question will be labeled as "Apple" My goal is to retrieve example.txt, search for Apple within it, and display the entire line where thi ...

What is the best way to capture user input using an onClick event in JavaScript and then display it on the screen?

I'm in the process of upgrading a table, and while most of it is working fine, there is one function that's giving me trouble. I want this function to return an input with an inline onClick event. The actual return value is displaying correctly, ...

Only enable the last day of each month on the React Material UI date picker, all other dates in the year should be disabled

I've been struggling to find a solution that allows users to only choose the last day of each month in a year, disabling all other days. After searching for answers using the Material UI date picker, I have not been successful. If anyone can guide me ...

Learn how to use AJAX to send a post request to PHP and dynamically load content into a specific

Recently, I have been working on developing a filter function using ajax and PHP. Although I am still quite new to ajax, I was able to create an HTML input that looks like this: <form> <input type="text" placeholder="Search" ...

Checking the status: Real-time validation of checkboxes using jQuery

I am currently utilizing the jQuery validation plugin known as jQuery validation. In my code snippet below, I have a straightforward validation method that checks the number of checkboxes that are selected based on a specified parameter: $.validator.metho ...

Exploring nested JSON data in Vue.js

In my attempt to access nested JSON within an array using Vue for a simple search functionality, I encountered a problem. Each school is encapsulated in a "hit" array, causing the system to perceive only one result of "hit" instead of returning data for ea ...

Unable to generate new entries with HTML Form

I've been working on creating a simple form with the ability to add new seasons or entries that will be posted to a database, but I've hit a roadblock. Whenever I try to run it, the "Add more Episodes" buttons for new seasons don't seem to w ...