How can I make <p> elements change color when scrolling?

My Goal

https://i.sstatic.net/JbdXR.gif
I aim to bring attention to the <p> element as the user scrolls on the page.
Initially, the opacity is set to 0.3, but I want it to change to 1 gradually as the user scrolls down.


My Attempt

window.onscroll = function {scrHL};

function scrHL() {
  if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
    document.querySelector('.main-p p').style.opacity = '1';
  } else {
    document.querySelector('.main-p p').style.opacity = '.3';
  }
}

However, this code didn't achieve the desired effect. What am I missing?
How can I toggle the highlighting of <p> each time a scroll event occurs?


Current Situation

https://i.sstatic.net/knLUh.gif
The current state is not producing the expected highlight when changing the numbers within the code. Why is that happening?


The Code

HTML

<div class="mai">
  <section class="main-p"><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>

  <p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>

  <p>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
  <p>Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p></section>
</div>

CSS

.mai {
  margin: 2.8rem 0 0 0;
  height: 37.8rem;
  overflow-y: scroll;
  overflow-x: hidden;
  -ms-overflow-style:none;
}
.mai::-webkit-scrollbar {
  display:none;
}

.main-p {
  white-space: pre-wrap;
}

JS

window.onscroll = function {scrHL};

function scrHL() {
  if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
    document.querySelector('.main-p p').style.opacity = '1';
  } else {
    document.querySelector('.main-p p').style.opacity = '.3';
  }
}

Answer №1

Check out this simple demonstration, give it a try in full screen mode (click on the full screen link once you run the snippet)... I believe it will meet your requirements perfectly :)

// Set boundaries for highlighting
// Suggest creating a 'highlighter area' related to an element
var highlight_from = 200;
var highlight_to = 400;

$(document).ready(function(){

  $(document).scroll(function(){

    trackScroll();

  });

  // Highlight something at the beginning when the page loads
  trackScroll();

});

function trackScroll() {
  var scrollTop = $(window).scrollTop();

  $("p").each(function(i) {

    $("p").eq(i).removeClass("highlight");

    var pos = $("p").eq(i).position()['top'] - scrollTop;

    if ((pos > highlight_from) && (pos < highlight_to))
    {
      $("p").eq(i).addClass("highlight");
    }
  });
}
p {opacity: 0.3; }
.highlight { opacity: 1 !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus eget finibus mauris, malesuada maximus urna. Aliquam tristique augue hendrerit ultricies commodo...</p>

<p>Cras venenatis iaculis ex, in elementum neque suscipit quis. Morbi diam ipsum, cursus id dictum et, rhoncus non purus. Donec vitae dui eu neque faucibus varius...</p>

<p>Maecenas sed ipsum ac lacus porta finibus auctor a arcu. Suspendisse convallis massa ut orci commodo, et vulputate mauris cursus. In iaculis convallis lorem...</p>
<p>Fusce eu bibendum velit. Praesent at sem imperdiet, condimentum diam imperdiet, tempor enim. Nam vitae mattis massa. Donec malesuada quis magna in finibus. Aenean ac...

Answer №2

Let's delve into the Intersection Observer API—an innovative solution provided by browser vendors to alleviate the challenges associated with traditional scroll binding.

As mentioned on MDN:

The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's viewport.

Here is a demonstration:

// Fires when element or elements appear in the viewport
function onEntry(entry) {
  entry.forEach(el => {
    if (el.isIntersecting) {
      el.target.classList.add("visible");
    }
  });
}

// Instantiate a new Intersection Observer
let observer = new IntersectionObserver(onEntry);

// All paragraphs
let elements = document.querySelectorAll("p");

for (let elm of elements) {
  observer.observe(elm);
}
p {
  line-height: 1.25;
  font-family: helvetica;
  opacity: 0.3;
  transition: 0.8s opacity 0.15s ease-in-out;
}

p.visible {
  opacity: 1;
}
<p><strong>What's up, POP?</strong></p>
<p>
  Lorem ipsum dolor sit, amet consectetur adipisicing elit.... [Truncated for brevity]
</p>
[Repeating paragraph content for display purposes]

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

Exploring the features of the AJAX event object within a callback setting

I have successfully implemented the Aquantum jQuery plugin for file uploads on my LAMP site. While it works well, I am now looking to add a success callback function that can insert both the uploaded filename and file URL into a form field. You can find ...

Creating an internal link to navigate to a specific element ID within another Angular component

Seeking Solution I am facing a challenge in using an internal link within the <a> tag to navigate to a specific section of another component by HTML ID. My Exploration First, I visited this site: https://www.w3schools.com/html/html_links.asp bu ...

Problem with Jquery Sticky Navigation

I've been struggling to understand this issue and can't seem to find any help. http://fiddle.jshell.net/DQgkE/7/show/ The user experience is currently a bit glitchy, but what I would like is: 1) When scrolling down the page, I want the Sticky ...

Switching the visibility of multiple textareas from block to none

I am currently exploring ways to make one text area disappear while another one appears in its place. With limited knowledge of Javascript and just starting my journey into HTML and CSS, I am reaching out to the forum for assistance or guidance on the rig ...

JavaScript code is functioning properly on Chrome and Internet Explorer, however, it may not be working on FireFox

Despite searching through the console, I am unable to find a solution to this issue. There are two images in play here - one is supposed to appear at specific coordinates while the other should follow the mouse cursor. However, the image intended to track ...

To ensure a successful redirection process without information loss, it is essential to address any potential issues with data input into

How can I properly implement a page redirection? Below are the relevant code snippets. <link rel="stylesheet" type="text/css" href="payout.css"/> <font face='calibri'> <?php session_start(); $conn = @mysql_connect("localho ...

Concerns with combining key value pairs in Typescript Enums

Could you help me figure out how to properly implement an enum in my drop-down so that I can only display one value at a time? Currently, I am seeing both the key and the value in the list. This is my enum: export enum VMRole { "Kubemaster" = 0, "Kub ...

What is a method to prevent a div from being rendered in CSS, rather than simply hiding it from view

Although I am aware that the div can be hidden using CSS, its persistent existence is causing layout issues. Is there a way to completely eliminate any rendering of the div so that it ceases to exist? ...

Modify the size value dialog during runtime

I am attempting to create a property or method that can change the size of my container dialog built using Vuetify. Initially, I need it to look like this: <v-flex xs12 md10> I believe that by creating a variable property, I can dynamically change ...

Troubleshooting a CSS layout problem: Organizing a webpage layout using CSS that includes an

I am currently facing an issue with arranging a container inline and it seems like there is something missing in my CSS code. After applying float:right, the class "second" does not seem to work as expected. Here's how my container is structured: &l ...

Assess html code for Strings that include <% %> tags along with embedded scripts

Having a small issue with my code where I am receiving an HTML response from a web service as a java String. I need to display this String as HTML on my webpage, but the problem is that there are some script tags in the form of <% ... %> which are sh ...

Node.js equivalent of hash_hmac

I am facing an issue while trying to sign the URL in a Node.js application similar to how it is done in my PHP app. In PHP, I use the following code to sign the URL: private static function __getHash($string) { return hash_hmac('sha1', $stri ...

Serialize the selected options in a form from multiple select boxes

I have several select boxes on the webpage, each starting with the same prefix in their name attribute. My goal is to iterate through all select boxes on the page that start with SELECT___, retrieve the name of the select box and the selected option value, ...

Do not open iframe links in a new window

Is it possible to manipulate the iframe so that links open inside the iframe window? I want the links clicked within the iframe to stay within the same window instead of opening in a new one. However, I have too many links to individually edit their code ...

Issue with Ajax call not properly updating the DIV section within the designated refresh interval

Seeking assistance. I have a JSP file that includes an AJAX call to DIV 'alertDIV'. I need this DIV to refresh every 3 seconds. The objective is to load the jsp file 'alertbar.jsp' every 3 seconds, which runs a query and returns results ...

Vue - when multiple parents share a common child component

Is there a way in Vue.js for multiple parents to share the same child component? I am looking to have multiple delete buttons trigger a single modal with different content. For example: myfile.html: <table id="app" class="table table-striped table-s ...

AngularJS - Array binding issue not updating in directive

I am currently developing a directive that has the ability to display a series of controls. Each individual control is implemented as a directive named fsFilter. In the controller managing the parent element, I establish a binding between the filters arra ...

How come this particular design is being passed down from a predecessor (and not a direct parent) div?

Web development can be frustrating at times. Hopefully, someone out there can shed some light on this issue and offer a solution. You can view the HTML/CSS code below or check out this example on JSFiddle The problem arises when I have a header div and a ...

What is the best way to insert a two-worded value into the value attribute of an input tag using Express-Handlebars?

Currently, I am using the code below to render the handlebars page: router.get("/update", function(req, res) { mysql.pool.query("SELECT * FROM workouts WHERE id = ?",[req.query.id], function(err, rows, fields) { if (err) { c ...

Comparing jQuery and Yahoo UI API Design

I find myself puzzled by the contrasting design approaches of jQuery and Yahoo UI APIs. I must confess, I have a strong aversion to the jQuery API, but my knowledge in web programming and JavaScript is limited, so I could be completely mistaken and end up ...