Numerous objects come into view as you scroll

I found a code snippet online that animates items as they appear on scroll. However, the code only triggers animation for one item at a time. How can I modify the code to trigger the animation for all items?

const observer = new IntersectionObserver(entries => { entries.forEach(entry => { const p = entry.target.querySelector('p'); if (entry.isIntersecting) { p.classList.add('down'); return; } p.classList.remove('down'); }); }); observer.observe(document.querySelector('.lol'));
@keyframes down { 0% { margin-top: -75px; opacity: 0; } 100% { margin-top: 0; opacity: 1; } } .down { animation: down 1s; }
<div class="lol"> <p>Phasellus efficitur facilisis suscipit...</p>
</div>

<div class="lol"> <p>Phasellus efficitur facilisis suscipit...</p>
</div>

<div class="lol"> <p>Phasellus efficitur facilisis suscipit...</p>
</div>

Currently, only the top paragraph triggers the animation effect upon scrolling. My goal is to have all paragraphs animate when scrolled into view.

Answer №1

At this moment, the only element being observed is document.querySelector('.lol'). Since the .querySelector method returns the first matching element based on the CSS selector provided, only the initial element with the .lol class is being monitored.
To observe all elements with the .lol class, you can use the .querySelectorAll method and iterate through the resulting nodeList:

document.querySelectorAll(".lol").forEach( element => {
    observer.observe(element);
} );

Another issue to address is the fluctuation in page height when observing elements. This can lead to a visually unstable screen as the height keeps changing. To resolve this, maintain a consistent page height by avoiding margin adjustments and instead repositioning elements using the CSS transform property:

@keyframes down {
    0% {
        transform: translateY(-75px);
        opacity: 0;
    }
    100% {
        transform: translateY(-0px);
        opacity: 1;
    }
}

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

Ways to customize PreBid.js ad server targeting bidder settings

In an effort to implement a unique bidder setting key name within my prebid solution, I have taken the necessary steps as outlined in the documentation by including all 6 required keys. Is it possible to change the key name 'hb_pb' to 'zm_hb ...

Sending JSON data stored in a JavaScript variable through a jQuery POST request

I am currently attempting to retrieve data from a remote location using a JQuery post method. It works perfectly fine when I directly input the data to be posted, but for some reason, it fails when I store the JSON in a JavaScript variable and pass it in. ...

What is causing the error message stating that the DateTime class object cannot be converted to a string?

I found this code snippet on a programming forum function increaseDate($date_str, ${ $date = new DateTime($date_str); $start_day = $date->format('j'); $date->modify("+{$months} month"); $end_day = $date->format(&apo ...

Having success loading JSON with AJAX in a local browser, however encountering issues when attempting to do so within the PhoneGap

When I try to load external JSON-data locally in my browser, it displays the data successfully. However, when using a cloud-based build service like PhoneGap for iOS and Android apps, the page loads but without the JSON-data appearing. Can anyone provide a ...

Using the POST method in Node.js is not functioning properly on the Replit server when using express

Recently diving into the world of backend development, I have been utilizing Node.js on a Replit server with express to host an application for handling files: However, hitting a roadblock when attempting to execute a post request! var express = ...

The back-to-top button guides users back to their last visited page

I'm excited to explore AngularJS and I want to add two "return to top" buttons on different pages. Here's what I have so far: Page 1: <h1 id = "top"> .......... <a href="#top" target = "_self">Return to Top</a> Page ...

Sending request results to the client's browser in Node.js - A step-by-step guide

I am struggling with figuring out how to send the results of a 'request' to the client browser. This function is executed on my Node.js server. var request = require("request"); function RedirectReceiver(url, currentState, callback){ ; Send ...

There was an issue with the Google Maps embed API that resulted in an error with interpolation

My goal is to utilize the Google Maps API in order to showcase a map using data from a JSON file. However, whenever I attempt to incorporate the JSON data, an error message 'Error: [$interpolate:noconcat] Error while interpolating' pops up. < ...

Sustain unbroken websocket connection with Discord using Node.js

I've been working on developing a Discord bot using the raw API, but I've encountered an issue where the bot stops functioning after some time. I suspect that this is due to neglecting to maintain the websocket connection. How can I ensure that ...

The functionality of Vue.js checkboxes is not compatible with a model that utilizes Laravel SparkForm

I've configured the checkboxes as shown below: <label v-for="service in team.services"> <input type="checkbox" v-model="form.services" :id="service.name" :value="service.id"/> </label> Although they are displayed correctly, the ...

Optimizing Your HTML/CSS/JavaScript Project: Key Strategies for Modular

When it comes to web frontend projects (html/css/javascript), they are often perceived as more complex to read and maintain compared to Java/C#/C/C++ projects. Is it possible to outline some optimal strategies for enhancing the readability, modularizatio ...

The Bootstrap Grid Leaves Blank Spaces Unfilled

View the screenshot here Take a look at the image above. I'm struggling to fill the empty space with div elements. I've experimented with display:inline-block and other display properties, but they haven't yielded the desired results. < ...

Troubleshoot your Vue.js application using Visual Studio Code. Encounter an unidentified breakpoint error

I'm encountering a problem with debugging my Vue.js project using VS Code and Chrome. I followed the official guide on the website Guide, but it's not working for me. The error I keep running into is: unverified breakpoint What am I doing wrong? ...

Content not being hidden by Twitter Bootstrap tabs

I am encountering an issue with my code. When I click on an inactive tab, the content of the first tab does not hide and both tabs' content is displayed simultaneously. Is there a solution to this problem? Thank you for your help! <ul style="l ...

Utilizing a Material UI custom theme in React with Typescript: A step-by-step guide

Upon using the tool , I received a js file and a json file following the paths mentioned on the theme generator page: // src/ui/theme/index.js /* src/ui/theme/theme.json */ The files operate smoothly when left with the .js extension. However, when I attem ...

Codeigniter's email functionality struggles to successfully deliver HTML-rendered content to Yahoo and LiveMail

Our codeigniter site utilizes the CI mail library to send emails. While Gmail displays the emails properly formatted, Hotmail and Yahoo only show the raw HTML code. The HTML template is called from a file named: emailer_temp.php <!DOCTYPE> < ...

Tips for correctly saving an array to a file in node.js express using fs module

I have been attempting to write an array to a file using node.js and angular for assistance, you can refer to the provided code in this question. Whenever I send the array, the file displays: [object Object],... If I use JSON.stringify(myArr) to send my ...

Tips for displaying a jQuery error message when a key is pressed

I am working with a textarea that has a word count limit of 500. I need to display an error message below the textarea if the word count exceeds 500. I have successfully calculated the word count, but I am unsure how to display the error message and preve ...

How to change the image source using jQuery when hovering over a div and set its class to active?

I am working with a div structure that looks like this: <div class="row margin-bottom-20"> <div class="col-md-3 service-box-v1" id="div1"> <div><a href="#"><img src="path" id="img1" /></a></div> ...

Sending JSON Data over URL

I am facing a challenge with passing data between two HTML files. My initial solution involved sending the data through the URL using the hash and then parsing the link using JSON.parse(window.location.hash.slice(1));. This method worked for a few attempts ...