Adding a class using jQuery based on whether a section is visible or hidden on the screen

Seeking advice on the best approach to take.

Division 1 or section - Apply style 1 if division 1 is currently visible on the screen.

Division 2 or section - Apply style 1 if division 2 is currently visible on the screen.

Division 3 or section - Apply style 2 or class 2 if division 3 is currently hidden from the screen.

Division 4 or section - Apply style 1 or class 1 if division 4 is currently hidden from the screen.

Any suggestions would be greatly appreciated.

Answer №1

My initial goal was to explore the various functions available in JavaScript.

Upon conducting further research on the subject, I came across the intersection observer, which appears to be a fantastic option leading to faster load times.

The concept of implementation is outlined below, and any suggestions for improvement are welcomed.

I am relatively new to JavaScript and am eager to challenge myself with UX scripting.

//const primary = document.querySelector('.primary');
//const secondary = document.querySelector('.secondary');

const sections = document.querySelectorAll('.secondary');
const options = {
root: null, //it is the viewport
threshold: 0.25,
rootMargin: '-15% 0%  -15% 0% ',
};

const observer = new IntersectionObserver(function (entries, observerer) {
entries.forEach((entry) => {
//console.log(entry.target);
//entry.target.classList.toggle('inverse');
if (entry.isIntersecting) {
document.body.classList.toggle('inverse');
}
});
}, options);

sections.forEach((section) => {
observer.observe(section);
});
* {
margin: 0;
padding: 0;
}
section {
width: 100%;
height: 100vh;
transition: background-color 1s ease;

border: 1px solid;
}

:root {
--primary: #f4f4f4;
--secondary: #191918;
--accent: #f9cdcd;
}

body {
background-color: var(--primary);
color: var(--secondary);
transition: background-color 1s ease, color 1s ease;
will-change: background-color, color;
}
h1 {
text-align: center;
padding-top: 50px;
font-size: 4rem;
}

.primary {
display: inline-block;
}

.secondary {
display: inline-block;
}

.accent {
display: inline-block;
}

.inverse {
background-color: var(--secondary);
color: var(--accent);
transition: background-color 1s ease, color 1s ease;
will-change: background-color, color;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>IntersectionObserver</title>
<link rel="stylesheet" href="./intersection_observer.css" />
</head>
... (html code continues)
...

Ak

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

Convert numerical values to currency format

Here is a number 5850 that I would like to format as currency. Format Example 1: 5850 => $58.50 Format Example 2: 9280 => $92.80 I am utilizing the function below: Number.prototype.formatMoney = function(decPlaces, thouSeparator, decSeparat ...

Issue with Laravel 5 Application: AJAX POST Request failing to accept token and resulting in a 500 internal server error

After spending nearly 3 hours troubleshooting, I still can't figure out why my code isn't functioning properly. It seems like my ajax request is failing to recognize the CSRF token despite trying various methods to include it. This is my first ex ...

Error: Attempting to retrieve a refresh token from the Google API resulted in an Uncaught ReferenceError, as the

I am currently working on obtaining a refresh token once a user authorizes with Google in order to prevent the need for re-authorization. After studying Google's documentation, I learned that setting the access type to offline is necessary. Now, I am ...

Styling a Fixed Header in CSS/HTML - Scroll Effect

Is it possible to hide only the upper part of the nav-bar, similar to the behavior in WhatsApp? I am using material-ui for this particular use-case. Currently, my implementation causes the app-bar to extend only when the scroll position is less than 48px, ...

React router updates the URL without affecting the actual display

I am facing an issue in my React project where the URL changes when clicking a link, but the view does not update. I have a separate route and links file, and I can't seem to figure out the problem. Here is my index.js: import React from 'react ...

Choose from the Angular enum options

I am working with an enum called LogLevel that looks like this: export enum LogLevel { DEBUG = 'DEBUG', INFO = 'INFO', WARNING = 'WARNING', ERROR = 'ERROR' } My goal is to create a dropdown select el ...

How to place a scrollable content below a fixed flexbox navigation menu

I am struggling with a certain snippet (best viewed in full screen mode) where I need to position the <main> element directly underneath the <header> element. The <header> is set in a fixed position to remain at the top of the screen whil ...

Progressively modifying related elements over time intervals

I have a specific list of p elements in my HTML code that I need to modify sequentially with a time interval of 1 second. Here is the HTML: <p>Changing first sentence!</p> <p>Second sentence ready!</p> <p>Third one coming up ...

Determine whether there is text present on a webpage using JavaScript

I am familiar with Python coding from selenium import webdriver driver = webdriver.Chrome() driver.get('http://WEBSITE') assert 'TEXT' in driver.page_source However, I now require the equivalent JavaScript code. ...

Exploring the power of ElasticSearch alongside Mysql

As I plan the development of my next app, I am faced with the decision between using NoSQL or a Relational Database. This app will be built using ReactJS and ExpressJS. The data structure includes relational elements like videos with tags and users who li ...

Error Handling with Node.js Sequelize RangeError

Currently, I am in the process of setting up a table to store user sessions. Specifically, I plan to save the IP address as an integer and have been exploring various methods for achieving this. You can find more information on this topic here: IP-addresse ...

Close ui-bootstrap typeahead menu only when a row is manually chosen

I have set up this jsBin to show the problem I am facing. When you visit the link and try to type "Five," the expected behavior would be to type "Five" and then press tab. However, in this case, you need to type "Five" and then either escape or click outsi ...

Manipulating the Datepicker onChangeMonthYear event in Jquery UI

I am currently working on customizing the appearance of specific dates within a jQuery UI datepicker. If a date is considered a holiday (meaning it matches a date in an array of specified holiday dates), I want to remove the default styling and make some m ...

"Divs are now linked and drag as one cohesive unit instead of

As I was experimenting with making images draggable and resizable, I encountered a small issue. When I attempted to drag two or more images, they would merge into one large draggable object instead of remaining separate. My goal was to make each image drag ...

Utilize Google's Places Direction API Autocomplete feature to pre-select the starting location

I am currently utilizing draggable markers along with 2 autocompletes to assist with obtaining directions. You can find more information about this setup here: https://developers.google.com/maps/documentation/javascript/examples/directions-draggable. With ...

Dividing a string into an array and displaying it in a table using Laravel

Retrieving a string from the database and using the explode function to split the values. Below is the code snippet: $data = DoctorRegistration::select('products') ->where('doctorid','=',$doctorid) ->get(); ...

Fade images using jQuery when hovered over

Is there a way to create an interactive image that cycles through multiple images when hovered over, and returns to the original image when the mouse moves away? I'm aiming for a smooth fade effect between images, like transitioning between 3 or 4 dif ...

Despite the status being 500, Chai is successfully navigating the test cases

I'm currently conducting test cases for my API using Chai, Mocha, and Chai HTTP. Even when I return a response of 500, my test case is still passing. Below is my test case: describe('/POST saveBatch', () => { it('it should save ...

How do I make an element stay in place between two other elements?

Trying to make an element "float" between two other elements using the `position : sticky` attribute. Not achieving the desired effect and unable to determine why. The goal is for the `copy` to float between the bottom of `upper` and the top of `lower`. ...

Enable JSON Data Management through Express

I am utilizing the lowDB dependency to manage JSON data in conjunction with Express, and for the most part, it is functioning properly. However, I have encountered a bug that I am struggling to resolve. I have created a /create page where users can input ...