Guide on triggering CSS @keyframes animations upon element visibility while scrolling

I'm struggling with controlling CSS animations that I want to start only when the element becomes visible on the screen. The issue arises because I have a website with a total height of around 8000px and the element with the animation is located far down the page. Therefore, every time I scroll down to view the element, the animation has already begun and is ending.

I've searched for solutions on platforms like Stack Overflow and YouTube, but unfortunately, none of the methods I tried worked, and I'm close to giving up.

Does anyone know how to trigger the animation only when the element is visible? Can someone guide me on the correct JavaScript code?

On a side note, this is my first website, and I didn't have formal training in HTML, CSS, or JavaScript/jQuery in school or university, so please excuse any unconventional class or ID names and less-than-professional solutions. HTML and CSS were relatively easy to learn, but JavaScript is proving to be challenging.

Below is the HTML element:

<article id="pasek">
  <div id="border_left" class="tekst"></div>
  <div id="litery" class="tekst">
    <p class="rok_założenia">2020</p>
    <p class="tekst_rok_założenia">Rok założenia</p>
  </div>
  <div id="border_right" class="tekst"></div>
</article>

CSS code for the article with id="pasek":

#pasek {
  text-align: center;
  background-color: #f4d03f;
}

p.rok_założenia {
  font-size: 80px;
  color: #154360;
  padding-top: 40px;
  padding-bottom: 5px;
}
p.tekst_rok_założenia {
  font-size: 40px;
  color: #154360;
  padding-bottom: 40px;
}

div.tekst {
  display: inline-block;
  animation-name: fade-in;
  animation-duration: 3s;
}

@keyframes fade-in {
  0% {
    opacity: 0;
    transform: translateY(20px);
  }
  100% {
    opacity: 1;
    transform: translateY(0px);
  }
}

#border_left {
  border-right: 2px solid;
  height: 120px;
  border-right-color: white;
}

#border_right {
  border-right: 2px solid;
  height: 120px;
  border-right-color: white;
}

#litery {
  padding-left: 70px;
  padding-right: 70px;
}

Answer №1

There's an interesting piece on CSS-Tricks detailing how to achieve this effect using jQuery.
I tweaked your code example regarding IDs to enhance flexibility and created a live preview of the result.

If you're interested in expanding your knowledge of JavaScript, consider exploring courses on platforms like Udemy, FreeCodeCamp, Frontend Masters, Pluralsight, and more.

Feel free to check out the live demo here: https://codesandbox.io/s/wizardly-noether-ed4pd

Answer №2

My Attempt with JavaScript:

Original:

 <script>
        $(document).ready(function(){
            $('.dummy').viewportChecker({
                callbackFunction: function(elem, action){
                    setTimeout(function(){
                        elem.html((action == "add") ? 'Callback with 500ms timeout: added class' : 'Callback with 500ms timeout: removed class');
                    },500);
                },
                scrollBox: ".scrollwrapper"
            });
        });
    </script>

Revised Code (changed class names, ids)

<script>
        $(document).ready(function(){
            $('.tekst').viewportChecker({
                callbackFunction: function(elem, action){
                    setTimeout(function(){
                        elem.html((action == "add") ? 'Callback with 500ms timeout: added class' : 'Callback with 500ms timeout: removed class');
                    },500);
                },
                scrollBox: "#pasek"
            });
        });
    </script>

I have also experimented with implementing these solutions: https://jsbin.com/zuqexigepe/edit?html,output http://jsfiddle.net/toby3105/749yxgdk/2/

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

The Backbone.js template does not automatically inherit attributes from the model

Hey there, I'm currently working on setting up a simple SPA using Backbone for testing purposes. However, when I try to render my view, the Underscore template doesn't seem to be picking up any attributes from my model. I've been trying to t ...

Finding the webpage URL where a form element is located

Suppose I have two pages called a.php and b.php, each with a form-tag. Both of these forms have the same action attribute set to c.php. Is there a way to determine in c.php which form (from either page a or b) triggered its submission? Using a hidden inpu ...

Are there any methods to create a circular z-index?

Is there a way in CSS to arrange #element-one above #element-two, then #element-two above #element-three, and finally #element-three above #element-one? Are there alternative methods to achieve this layout? ...

How to iterate through the elements of an object within an array using Vue.js and TypeScript

There was an issue with rendering the form due to a TypeError: Cannot read properties of undefined (reading '0'). This error occurred at line 190 in the code for form1.vue. The error is also caught as a promise rejection. Error Occurred <inpu ...

Issue with the Edit feature causing conflicts with the local storage and generating error messages

There seems to be an issue with my edit function that is causing it to override the local storage when I attempt to save and interfering with my delete function as well. I have searched through similar posts for a solution but have not been able to pinpo ...

Choose all div elements except for those contained within a certain div

Having trouble with an IE7 z-index fixer that's affecting specific elements. I'm attempting to select all divs, excluding those nested within a particular div. Below is the jQuery code I'm using, but it's not functioning correctly: & ...

Is it feasible to add to an ID using ngx-bootstrap's dropdown feature?

In the documentation for ngx dropdown, there is a feature called "append to body." I recently tried changing this to append to a table element instead and it worked successfully. Now, on another page, I have two tables displayed. If I were to assign each ...

The React component is experiencing a delay in its updates

I've been experiencing delayed updates when using React.useEffect(). Can anyone shed some light on why this might be happening? function Process(props) { const [results, setResults] = React.useState({ number: "", f: {} }); let ...

The functionality of JSON.stringify does not take into account object properties

Check out the example on jsfiddle at http://jsfiddle.net/frigon/H6ssq/ I have encountered an issue where JSON.stringify is ignoring certain fields. Is there a way to make JSON.stringify include them in the parsing? In the provided jsfiddle code... <s ...

create a new button with specific functionality and properties

Currently, I am working on a table that retrieves data from MySQL and displays it. Users have the ability to add new information, which is then appended using Ajax. One issue I encountered is that each row in the table contains a delete button. Although I ...

Divide and conquer- Lighttpd's mod_wstunnel combines separate messages by using UNIX socket communication to the backend server

In my experience with lighttpd's mod_wstunnel, I have encountered a peculiar issue. When I send two messages in quick succession from the backend using a UNIX socket to communicate between lighttpd and the backend, I noticed that lighttpd logs show th ...

Utilize CSS in the same way as the legend tag styling

I'm looking to create a stylish border around my HTML component. While I know the HTML legend element can achieve this, I want to use it outside of a form. For reference on using HTML Legend: http://www.w3schools.com/tags/tryit.asp?filename=tryhtml ...

Creating a full-width input field with text aligned to the right:

.wrap { white-space: nowrap; } input { width: 100%; } body { /* just so you can see it overflowing */ border: 1px solid black; margin: 40px; padding: 10px; } <span class="wrap"><input type="text">.pdf</span> Observing the cod ...

Looking to extract, interpret, and display PDF documents using React?

I'm working on displaying a PDF file from an external URL. My goal is to extract text from the PDF for analysis, and then present a specific section of a page to users in my React application. This will involve cropping the content using coordinates o ...

Updating a div using PHP elements

Currently, I'm using a webcam to capture images for a project related to learning. My goal is to showcase the recently taken photos. After taking a photo, it gets stored in a folder. To display all the collected photos within a <div>, I need to ...

Definition of Angular 2 File

I have developed a custom Gantt chart library using D3 in vanilla JavaScript. Now, I am trying to integrate it into my Angular 2 application. After installing D3 via npm and adding the necessary type files and the Gantt chart module to node_modules, I enco ...

What is the process for executing JavaScript in a secondary thread in V8?

In the v8 engine, JavaScript code is only able to run in the main thread. My goal is to run JavaScript code in a non-main thread so that CPU-intensive tasks cannot interrupt the CPU time of the main thread. However, I am currently at a loss on how to accom ...

Guide on sending several HTTP requests from a Node.js server with a shared callback function

Is there a way to efficiently make multiple HTTP calls in a Node.js server with a shared callback function? Are there any modules or libraries that can help with this? ...

Unraveling nested JSON structures with varying formats in Javascript or Jquery: Step-by-step guide

var cart = [ { "Items": "", "category": "", "contents": [ { "Apple iPhone": "222", "French": "Bounjour", "id": 1234, "icon": "/images/bg.jpg", "callback": "use()", "pricetag":"false" } ] }, { "Items": "No 2" ...

I am trying to confirm in PHP whether any of the gender checkboxes have been selected. However, the code I have tried so far does not appear to be functioning as expected

Please refrain from suggesting the use of checked = "checked" in HTML, as the validation must be performed in PHP as per the requirements of my assignment. PHP Code: if (isset($_POST["gender"])) { $gender = $_POST["gender"]; if (($gender != "male") || ( ...