What is the best way to dynamically load content as it enters the viewport using JavaScript or jQuery?

I have implemented a stunning animation to the h1 element using a function, but now I want the animation to trigger only when the h1 element enters the viewport as the user scrolls down.

Currently, the animation occurs as soon as the page is loaded, even before the user gets to that section.

My goal is for the animation to play dynamically and precisely when the h1 element becomes visible on the screen.

Answer №1

With Javascript's IntersectionObserver, you can be notified when a specific element enters the viewport.

This code snippet not only replicates the functionality of the code in the question but also waits for the text to become visible in the viewport before triggering the animation setup.

const textWrapper = document.querySelector(".text");
textWrapper.innerHTML = textWrapper.textContent.replace(
  /\S/g,
  "<span class='letter'>$&</span>"
);
let callback = (entries, observer) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {

      anime.timeline().add({
        targets: ".text .letter",
        translateY: [100, 0],
        translateZ: 0,
        opacity: [0, 1],
        easing: "easeOutExpo",
        duration: 2000,
        delay: (el, i) => 60 * i,
      });
    }
  });
};
let observer = new IntersectionObserver(callback);
observer.observe(textWrapper);
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.text .letter {
  display: inline-block;
  line-height: 1em;
}

.page1 {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.page2 {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>LNPD02</title>
  <link rel="stylesheet" href="styles.css" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/2.1.3/TweenMax.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.0.2/anime.min.js"></script>
</head>

<body>

  <div class="page1">
    <h1>Scroll down</h1>
  </div>

  <div class="page2">
    <h1 class="text">Animated Text</h1>
  </div>

</body>

</html>

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

Is it possible to generate a dynamic submenu and trigger events using the append method?

As I attempted to add a submenu within another submenu on a navigation bar, my goal was to have the submenu "reports management" appear when the Report option is clicked. Below is the code snippet I used. HTML <li class="drop-down"&g ...

The multiple lines text box displays an input box

Having a simple issue here, I've set the value of an input text box, but when the page loads it is displaying in multiple lines, and this seems to be happening only on Chrome browser. Can anyone offer any assistance? This is the HTML code for the ...

Getting the string value from query parameters can be achieved by accessing the parameters and

Currently, I am attempting to retrieve the string value stored within a class-based object variable named question5. The way I am trying to access this variable on the front-end is shown below. axios.get("http://localhost:3001/users/questionaire/?getq ...

The issue with CSS filter invert not functioning properly in Mozilla Firefox is causing complications

I am currently developing a small Firefox add-on designed to make reading pages at night more comfortable. The goal is to invert page colors without affecting images. Here is the code snippet I am using: document.body.style.filter = "invert(100%)"; var i ...

Submit Button in CKEditor Not Working Without Ajax Submission

Having an issue with the ckeditor. Downloaded the latest version and integrated it into my form like this: <form action="/news.php?frame=edit&amp;id=185" enctype="multipart/form-data" method="post" accept-charset="utf-8"> <textarea class="edi ...

Press the button using Selenium WebDriver with Java

Currently, I am utilizing Selenium Webdriver for Chrome and Firefox along with Java. After performing various actions, I stumbled upon a typical source code snippet like this: <input type="button" value="yoyo" class="btn" onClick="SubmitForm(this, &ap ...

Specify the return type based on specific parameter value

I'm facing a situation where I have two definitions that are identical, but I need them to behave differently based on the value of the limit parameter. Specifically, I want the first definition to return Promise<Cursor<T>> when limit is g ...

Erase jQuery from the text

I am struggling with splitting or removing text from a filename. For example, if I have filenames like: 200726100_50-0002.JPG 230514008_60-0001.JPG The desired result should be: 230514008_60.JPG 200726100_50.JPG Am I not using the split function cor ...

Discovering the identification of a comment in JavaScript

Here is the code snippet I am working with: <a onclick="lel($(this),'212345555')" class="button"> <a onclick="lel($(this),'241214370')" class="button"> <a onclick="lel($(this),'248916550')" class="button"> & ...

Display a PDF file within an IFrame using JavaScript and then print it

Why is it so challenging to achieve? I've dedicated 48 hours to research this, yet it seems impossible! Although recent Chrome versions allow the parent window to access PDFs in iframes, both FF and IE prevent any interaction with the iframe that dis ...

Utilize Angular 2 to search and filter information within a component by inputting a search term from another component

In my application, I have a Component named task-board which contains a table as shown below: <tr *ngFor="let task of tasks | taskFilter: searchText" > <td>{{ task.taskName }}</td> <td>{{ task.location }}</td> <td>{{ ta ...

jQuery: changing the order of list elements with the eq method

I've been tackling a challenge with designing a navigation bar that consists of 3 items. The goal is to have the clicked item move to the center position on the horizontal navbar while re-arranging the order. Here's the code snippet I've com ...

Is there a built-in constant in the Angular framework that automatically resolves a promise as soon as it

I'm facing a situation where I have code that checks a conditional statement to decide if an asynchronous call should be made. If the condition is not met, the call is skipped. However, I still need to perform some final action regardless of whether t ...

form_not_submitting_ajax

In the app I'm working on, I have a form that is defined in the following manner: = form_with model: project, remote: true, method: :put do |f| = f.select :selected_draw, options_for_select(project.draws.pluck(:number, :id), draw.id), {}, class: &a ...

Steps for implementing AJAX to display a success function and update database results in real-time

I'm struggling with allowing my AJAX call to send data to my PHP file and update the page without a reload. I need the success message to display after approving a user, but their name doesn't move on the page until I refresh. The goal is to app ...

Utilizing HTML 5 Canvas for QR Code Generation

Utilizing the repository qrcode to create QR codes. This is my Jquery code: $(".generatetext").click(function() { var x = document.getElementById("textdata").value; $('#output').qrcode(x); }); When clicking the "Generate Button," it cu ...

The validation error occurred with the expectation of a primitive boolean value

My starting point: I'm completely new to using booleans as a beginner developer snippet of code: const { SlashCommandBuilder, PermissionFlagsBits, PermissionsBitField, EmbedBuilder, } = require("discord.js"); const { ...

Exploring the Google Plus API: Discover individuals who are following a specific individual

Has anyone managed to successfully extract a list of individuals who have included a specific user in their circles or are following them on social media platforms? I am currently using the official JS Library for this task, but any solution in any progr ...

Turn off the background color box with a single click

Whenever I click on a header menu item, the background changes along with it. Is there a way to prevent this from happening? https://i.stack.imgur.com/p6bJ9.png Take a look here ...

The Ajax request yields a response consisting of an array filled with blank objects

Currently, I am utilizing PHP object-oriented programming to fetch data from the database. The data is retrieved successfully, but when I attempt to make AJAX calls, it returns an array of empty objects. How can I ensure that the objects return the actual ...