Exploring CSS3 animations: customizing animations for individual elements based on scroll movements

Can you help me with CSS3 animations triggered by scrolling?

I came across a code that reveals a DIV element as the user scrolls down:

    <script type="text/javascript">

            $(document).ready(function() {

        /* Every time the window is scrolled ... */
        $(window).scroll( function(){

            /* Check the location of each desired element */
            $('.hideme').each( function(i){

                var bottom_of_object = $(this).position().top + $(this).outerHeight();
                var bottom_of_window = $(window).scrollTop() + $(window).height();

                /* If the object is completely visible in the window, fade it in */
                if( bottom_of_window > bottom_of_object ){

                    $(this).animate({'opacity':'1'},500);

                }

            }); 

        });

    });

    </script>   

I'm working on a website with 5 different sections that should be revealed as the user scrolls to them. But I have a question about how to animate the contents within those boxes.

For example: In each box, there will be a title, content, and images. How can I make these elements appear one after another as the user scrolls? With the current code, all elements are shown at once.

I want the title to appear first, then the content, and finally the images when the user scrolls down. And this sequence should repeat for each box as the user navigates through them.

I've tried using CSS3 delays, but I can't predict how quickly users will scroll down.

Any tips would be greatly appreciated!

Answer №1

It's quite simple. Start by ensuring that the title, images, and content are each enclosed within their own div elements. Then, repeat the same process but focus on adjusting the positions and sizes of the individual divs. Check out this helpful jsFiddle link

$(document).ready(function () {
    $(window).scroll(function () {
        var bottom_of_window = $(window).scrollTop() + $(window).height();
        $('.title').each(function (i) {
            var bottom_of_object = $(this).offset().top + $(this).outerHeight();
            if (bottom_of_window > bottom_of_object) {
                $(this).animate({
                    'opacity': '1'
                }, 500);
            }
        });
        $('.innerImage').each(function (i) {
            var bottom_of_object = $(this).offset().top + $(this).outerHeight();
            if (bottom_of_window > bottom_of_object) {
                $(this).animate({
                    'opacity': '1'
                }, 500);
            }
        });
        $('.content').each(function (i) {
            var bottom_of_object = $(this).offset().top + $(this).outerHeight();
            if (bottom_of_window > bottom_of_object) {
                $(this).animate({
                    'opacity': '1'
                }, 500);
            }
        });
    });
});

Answer №2

Here is a potential solution using the callback function of .animate() and the .getBoundingClientRect() function:

HTML

<div style="height:900px; background:#abc;">example</div>
    <div class="hideme">
        <div class="title">heading 1</div>
        <div class="main">information 1
            <img src="/logo.png" />
        </div>
    </div>
    ...
</div>

JS

$(document).ready(function () {
  $(window).on('scroll resize', function () {
    var win_height = $(window).height();
    $('.hideme').each(function (i) {
      var elem_pos = this.getBoundingClientRect();
      var title = $('.title',this);
      var main = $('.main',this);
      var images = $('img',this);
      if ((elem_pos.top>win_height || elem_pos.bottom<0)) {
        title.css('opacity',0); // hide title
        main.css('opacity',0); // hide contents
        images.css('opacity',0); // hide images
        return true; // below or above viewport, continue
      }
      if (title.is(':animated') || main.is(':animated') || images.is(':animated')) {
        return true; // continue
      }
      title.animate({
        'opacity': 1
      }, 500, function(){
        main.animate({
          'opacity': 1
        }, 500, function(){
          images.animate({
            'opacity' :1
          },500);
        });
      });
    });
  });
});

Check it out on jsfiddle / View in fullscreen

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

Embedding an iframe with vertical scrolling enabled

Could you explain why I am unable to scroll the full width of the website? Here is a link: http://codepen.io/anon/pen/EKPaao?editors=1100. Also, what do you think about using this solution for adjusting iframes on different screen sizes? My iframe seems to ...

Send a string to the controller through an AJAX request

Seeking assistance on creating a search field to find users within my system. The idea is to input the user's name into the field, then use an Ajax function to pass that name from the search field to a method in the controller. This method will return ...

"Interactive bootstrap tabs nested within a dropdown menu that automatically close upon being clicked

Hey, I've got a dropdown with tabs inside. When I click on certain tabs within it, they close but the content inside the tabs that I click on changes, so it's functioning properly. However, the issue is that it closes when I want it to stay open ...

Switching the class from "untoggled" items to the selected item in React

Recently, I developed a toggle component known as Accordion. Within this component, I am iterating through an array of objects and displaying them in the following format: {object.map((o) => ( <Accordion key={o.id} title={o.question} className="i ...

Adding a panel dynamically with Bootstrap incorrectly

I have been using the Collapse panel in Bootstrap and it was working perfectly when implemented statically. However, I encountered an issue when trying to add it dynamically. HTML <form> <div class="form-group" > <label for="c ...

Getting the return value in JSP using JSP Ajax Servlet

When I click on one of the tables, another table is loaded using Ajax in my JSP: $("#tablesorter-demo tr").click(function(){ $('#tablesorter-demo tr').not(this).removeClass('hilite'); $(this).toggleClass(&apo ...

CSS Dynamix - Include the parameter ?value to resolve caching issues

I came across a discussion on the issue of Dynamic CSS caching problem where it was suggested to append ?value to the end of the css file name for better caching. I am currently using themes and the css files are loaded automatically. Is it possible to use ...

How to retrieve values from checkboxes generated dynamically in php using jquery

This is a unique question and not related to event binding or any suggested duplicates. Hello, I am facing an issue while trying to fetch the value of a checkbox to send it in an ajax request to a PHP page. The checkboxes are dynamically created using PHP ...

When the form is submitted, the text input vanishes and then the page is refreshed using AJAX technology

Can anyone help me troubleshoot why my page is reloading even though I used AJAX, and how to prevent it from clearing my input text after clicking the submit button? I tried using the show method to resolve this issue but it didn't work. <form met ...

Manage the placement of elements using CSS

Having an issue here. The blue-colored elements are showing up vertically, but I want them to be displayed horizontally. I've tried various methods but haven't been able to solve the problem. Providing just the code for the items below due to len ...

I am encountering a problem with IE11 where I am unable to enter any text into my

When using Firefox, I can input text in the fields without any issues in the following code. However, this is not the case when using IE11. <li class="gridster-form" aria-labeledby="Gridster Layout Form" alt="Tile Display Input column Input Row ...

Determining the value of an object property by referencing another property

Upon running the code below, I encounter the following error message: Uncaught TypeError: Cannot read property 'theTests' of undefined $(document).ready(function() { var Example = {}; Example = { settings: { theTests: $(&apo ...

This code is only functional on JSFiddle platform

I encountered an issue with my code recently. It seems to only work properly when tested on jsfiddle, and I can't figure out why it's not functioning correctly on codepen or when run from local files. Why is this code specific to jsfiddle? When ...

The addition of one-page navigation in Angular 7 seems to be experiencing some glitches

I recently added a new menu option to my Angular 7 project, but it's not functioning correctly. I used Bootstrap 4 and followed this example from here. Can anyone help me figure out the correct way to implement this? Check out the sample on StackBlit ...

Show two choices in a select box next to each other

I've been attempting to display a select box with two options side by side in a list format. Struggling to find any libraries that can achieve this functionality. Here is an example: <select> <option x><option y> <optio ...

Is there a method in JavaScript to prevent href="#" from causing a page refresh? This pertains to nyroModal

Is there a way to prevent <herf="#"> from causing a page refresh? I am currently working on improving an older .NET web project that utilizes nyroModal jQuery for displaying lightboxes. However, when I attempt to close the lightbox, nyroMo ...

Troubleshooting jPlayer Preload Problem

Currently, I am utilizing HTML5 jPlayer to play audios through a recursive method. While everything is functioning smoothly and the audio is playing, there seems to be a delay when loading the new audio. To eliminate this delay between audios, I aim to pr ...

The JSON object is not defined

I have a question regarding an AJAX page request using a PHP file to handle queries in my MySQL database. The PHP file seems to be working properly, but I am encountering some issues. Here is the code snippet: function updateForm(){ ID = $(&ap ...

Utilize jQuery to load a separate external sites div into an iframe

I have a department website that caters to a specific audience. I am interested in including a set of related links from an external site at the conclusion of each article. The links will be organized within a div, like so: <div id="linktoc"><a h ...

Vuetify's Handy Helper Classes

Hey everyone, I'm working on a vuetify project and I need to convert inline styles to utility classes (if possible) font-size: 24px; font-weight :600 I checked the documentation and noticed that it only provides options for setting size and weight wi ...