Enhance your webpage with dynamic styling using third-party CSS animation

Apologies for any similarity to other questions on this topic. I have searched extensively, but any assistance would be greatly appreciated.

I am utilizing a new animation library from Animista to animate specific elements on a test website. Animating elements upon page load is not an issue, but I am unsure how to make them trigger as they become visible, as is common on many websites nowadays.

For instance;

.bounce-in-top {
-webkit-animation: bounce-in-top 1.1s both;
        animation: bounce-in-top 1.1s both;
}

@-webkit-keyframes bounce-in-top {
  0% {
    -webkit-transform: translateY(-500px);
            transform: translateY(-500px);
    -webkit-animation-timing-function: ease-in;
            animation-timing-function: ease-in;
    opacity: 0;
  }
  38% {
    -webkit-transform: translateY(0);
            transform: translateY(0);
    -webkit-animation-timing-function: ease-out;
            animation-timing-function: ease-out;
    opacity: 1;
  }
  55% {
    -webkit-transform: translateY(-65px);
            transform: translateY(-65px);
    -webkit-animation-timing-function: ease-in;
            animation-timing-function: ease-in;
  }
  
  ...

.trigger {
  /* The plan was to add this to all elements and then trigger animations each time the class is in the viewport*/
}
<h1 class="bounce-in-top trigger">Page title, animates on load</h1>


...

<h2 class="bounce-in-top trigger">Lower down, should animate when visible</h2>

The animation is applied to both header 1 and header 2, but the header 2 animation runs before it's visible to the user.

.bounce-in-top {
-webkit-animation: bounce-in-top 1.1s both;
        animation: bounce-in-top 1.1s both;
}

@-webkit-keyframes bounce-in-top {
  ...

.trigger {
  /* The plan was to add this to all elements and then trigger animations each time the class is in the viewport*/
}
<h1 class="bounce-in-top trigger">Page title, animates on load</h1>


...

<h2 class="bounce-in-top trigger">Lower down, should animate when visible</h2>

I would like to use some form of query selector so that every time an element to be animated appears, its animation would run.

Any guidance and functional code would be immensely appreciated as I am struggling to implement this.

Thank you in advance.

Answer №1

In my opinion, it would be beneficial to monitor the scrolling behavior of the webpage and trigger an animation when the scroll position exceeds a specific point. This can be achieved by adjusting the CSS animation properties through JavaScript. Here's a simple illustration:

<html lang="en">
<head>
<style> 
    #header2 {
        width: 100px;
        height: 100px;
        background: red;
        position: relative;
        -webkit-animation: none 1s infinite; /* Safari 4.0 - 8.0 */
        animation: none 1s infinite;
    }
    /* Chrome, Safari, Opera */
    @-webkit-keyframes mymove {
        from {left: 0px;}
        to {left: 200px;}
    }


    @keyframes mymove {
        from {left: 0px;}
        to {left: 200px;}
    }

</style>
</head>
<body>
    <h1 id="header1" style="height: 1200px;">This is first paragraph</h1>
    <br>
    <h1 id="header2">This is second paragraph</h1>

    <script>
        let myHeader2 = document.getElementById("header2");
        window.setInterval(checkScrollingPosition, 200);

        function checkScrollingPosition(){
            console.log(window.scrollY)
            if (window.scrollY > 200){
                //starting animation if scrollPosition > 200
                console.log("starting animation...")
                startAnimation()
                return;
            }

        }

        function startAnimation(){
            myHeader2.style.animation = "mymove 5s 1"
            myHeader2.style.WebkitAnimation = "mymove 5s 1"
        }
    </script>

</body>
</html>

Depending on your requirements, you may adjust the threshold value to a percentage of the page's height. To do this, explore different methods of accessing the page's scrolling state.

Answer №2

Utilize the IntersectionObserver API to check if elements are within the user's view and trigger a function when they come into view.

Within the IntersectionObserver, call a function that iterates through all elements entering or exiting the view. This function allows you to inspect each element's current position individually.

To apply an animation to an element once it enters the view, check if the element is in sight and then add the animation class to it.

In the snippet below, I've updated your code by enclosing each title within a container. This setup enables the title to animate within its container while also controlling overflow.

The observer targets elements with the class .trigger. When these elements become visible, they receive the class .bounce-in-top.

To prevent abrupt animations starting from the top, I set a starting position for the .title elements equal to the initial keyframe of the animation.

// Create the observer.
const observer = new IntersectionObserver(entries => { // entries is a list of elements that have come in our out of view
  entries.forEach(entry => { // Loop over every single entry
     if (entry.isIntersecting || entry.intersectionRatio > 0) { // Check that an entry has come INTO view.
        entry.target.classList.add('bounce-in-top'); // Add the class to the element.
     }
  });
});

// Select the triggers
const triggers = document.querySelectorAll('.trigger');

// Observe the triggers.
triggers.forEach(trigger => {
  observer.observe(trigger);
});
/* Create a default begin state */
.title {
  -webkit-transform: translateY(-500px);
            transform: translateY(-500px);
}

/* Hide overflow of title container. */
.trigger {
  overflow: hidden;
}

/* Select title for animation */
.bounce-in-top .title {
-webkit-animation: bounce-in-top 1.1s both;
        animation: bounce-in-top 1.1s both;
}

@-webkit-keyframes bounce-in-top {
  /* Keyframe rules here */
}
@keyframes bounce-in-top {
    /* Keyframe rules here */
}
<div class="trigger">
  <h1 class="title">Page title, animates on load</h1>
</div>

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

Design with Internal Elements

Seeking a pattern similar to the code snippet provided below. Interested in learning how to create MyComponent. render(){ <MyComponent> <MyComponent.Something> These children will be displayed </MyComponent.Something> <MyC ...

Produces consistent results despite variations in tag names within the DOM

While iterating over each element (post) in an array, I have assigned each HTML tag name a value of post._id. In the DOM, the outputs have different values as expected. However, when I try to capture these values in the React Profile component, the console ...

Substitute all numerical values with a designated number from a variable

I came across a link that looks like this foo.net/index.php?page=15 My goal is to replace any number after page=xxx and retrieve the new number from a variable Currently, my code only replaces 15 with 16 var num = 16, // What if the str = foo.net/index ...

The error message "TypeError XXX is not a function in NodeJS" indicates that

As I attempt to enhance the testability of my NodeJS API by incorporating a service, a peculiar issue arises. Specifically, upon injecting the service (class), an error is triggered stating that the method getTasks() does not exist. ROUTE const TodoServi ...

The 'slice' method is not accessible with the Kendo Grid Object

Attempting to connect the kendo grid to a WCF remote odata service is proving challenging. The grid fails to populate, throwing an exception Object doesn't support property or method 'slice'. Here's the javascript code used to initializ ...

Embed a hyperlink within an informational passage

I have a search box with Ajax functionality like this; And I want to customize the NotfindText message to display as: "No results found, but you can try advanced search from here" However, I am struggling to add the link. I do not have much knowledge abo ...

In what specific format does this plugin expect the callback string to be encoded as? (jquery-ui-multisearch)

Currently, I'm working with a plugin named "Jquery-ui-multisearch" that provides an autocompletion feature in an input field based on either a provided array or an external source (such as ajax/api, etc). You can find more information about this plugi ...

The attempt to run 'readAsBinaryString' on 'FileReader' was unsuccessful. The first parameter is not the expected type 'Blob'

I am currently working on parsing an xls file. You can find the file by clicking on the following link: However, I am encountering an error that says: 'Failed to execute 'readAsBinaryString' on 'FileReader': parameter 1 is not of ...

JS Implementation of the Coin Change Algorithm

I've been grappling with this algorithm for the past few days, but unfortunately I haven't been able to come up with a successful solution yet. The available solutions seem to be too advanced for my current level of understanding. This problem mu ...

Even with the text field populated and clearly existing, Firefox is still throwing a null error when trying to retrieve it using

Hey there! I'm currently working on a sample HTML page and I'm facing an issue with retrieving data from a text field. No matter what I try, I keep encountering the following error: TypeError: document.getElementById(...) is null Let me share t ...

sending functions into angular as opposed to using 'function()'

Lately, I've been immersing myself in Angular development. One thing that caught my interest was the idea of using a declared function instead of a generic "function() {}" placeholder, particularly in scenarios like handling promise callbacks. I encou ...

``The presence of symlink leading to the existence of two different versions of React

Currently, I am working on a project that involves various sub custom npm modules loaded in. We usually work within these submodules, then publish them to a private npm repository and finally pull them into the main platform of the project for use. In orde ...

Trouble with integrating jQuery Mobile data-role page into a PHP project

Why am I encountering issues when trying to link to the data role page <div data-role="page" id="sessionrecordsuccess"> in the main.php file? Instead of directing me to the specific section, it keeps redirecting to the top of main.php. I have another ...

Unable to retrieve property from NextRequest

Currently, I am attempting to utilize MiddleWare in conjunction with Next.js's Middleware and JWT. Upon logging cookies and the typeof cookies variable, this is what I see on my console: { token: 'token='myToken'; Path=/' } obj ...

Utilizing CSS to dynamically update the nth-child selector

I've created an image gallery with a 2-column layout, allowing for full-width images to be interspersed between the columns. To see an example of this, check out my Codepen: <div class="gallery"> <img src="http://nosrc.io/200x200"> ...

What is causing the malfunction in jQuery version 1.7.x?

Here is a code snippet demonstrating the issue I am facing: var $div = $('<div>'); $('span').live('click', function() { this.innerHTML = 'changed'; }); $div.append( $('<span>span</span>& ...

Is there a way to incorporate a <u> tag into an inline angular variable in HTML that has been generated by a ternary expression?

Currently, I have the following scenario. <label> Make {{$ctrl.tcTemplate.isLibrary ? $ctrl.tcTemplate.name : "this item"}} a Library item: <toggle ng-change="changed(); $ctrl.eraseName();" ng-model="$ctrl.tcTemplate.isLibrary;" off="Fals ...

Encountering a problem with the multi-page template structure in jQuery Mobile

As a newcomer to Phonegap, I am utilizing jQuery Mobile and HTML5 for the development of an Android app. The app consists of three pages: the first page, index.html, displays a list of contents; the second page holds text content as well as a header with b ...

How can I adjust the scale and position of my image textures in Three.js?

Is there a way to adjust the scale and position of my image textures? The dimensions of my image are 1024px x 1024px. let textureMap = THREE.ImageUtils.loadTexture( 'texture.png' ); https://i.sstatic.net/wKd6f.jpg ...

Exploring the power of jQuery selector syntax with the inclusion of

There are multiple html structures similar to the one below: <div class="item"><p>...</p></div> I am looking to loop through them and select the p elements. I have tried different variations of the code below but couldn't get ...