Tips for triggering animations on nested content when the parent slide is animated and enters the viewport without relying on traditional scrolling methods

I would like to implement a JavaScript solution that will animate the content of a nested DIV within a parent slide when the parent slide comes into view.

Currently, the content in the nested DIV only animates when a scroll command is triggered after the parent slide enters the screen. I suspect this is because the slide motion is animated and not controlled by scrolling.

This same issue can be seen in a JSFiddle demo I set up to investigate further:

http://jsfiddle.net/9dz3ubL1/

(Please note that the sliding animation from right to left in the demo is simply for testing purposes and does not reflect the actual development features).

My question is, how can I create a script that triggers animations for each nested DIV whenever a slide element enters the viewport, without the need for a scroll event?

Any assistance would be greatly appreciated. Below is the script I am currently using to adjust opacity and other CSS styles.

$(document).ready(function() {
  /* Trigger animations when the window is scrolled */
  $(window).scroll(function() {
    /* Animating hidden_header with delay */
    $('.hidden_header').each(function(i) {
      var center_of_object = $(this).offset().left + $(this).outerWidth();
      var center_of_window = $(window).scrollLeft() + $(window).width();
      /* If the object is fully visible in the window, fade it in */
      if (center_of_window > center_of_object) {
        $(this).animate({
          'opacity': '1'
        }, 500);
        $(this).animate({
          'right': '0'
        }, 1500);
      }
    });
    /* Animating hidden_content with delay */
    $('.hidden_content').each(function(i) {
      var center_of_object = $(this).offset().left + $(this).outerWidth();
      var center_of_window = $(window).scrollLeft() + $(window).width();
      /* If the object is fully visible in the window, fade it in */
      if (center_of_window > center_of_object) {
        $(this).animate({
          'opacity': '1'
        }, 3000);
        $(this).animate({
          'bottom': '0'
        }, 3500);
      }
    });
    /* Animating button with delay */
    $('.button').each(function(i) {
      var center_of_object = $(this).offset().left + $(this).outerWidth();
      var center_of_window = $(window).scrollLeft() + $(window).width();
      /* If the object is fully visible in the window, fade it in */
      if (center_of_window > center_of_object) {
        $(this).animate({
          'opacity': '1'
        }, 5000);
      }
    });
  });
});

Answer №1

When your slide motion is fully animated (not incremental like in the jsfiddle provided), jQuery offers a way to execute an action once the animation is finished.

Check out the options available for the animate function on http://api.jquery.com/animate/. One of these options is called "done." By assigning a function to the done option, you can have that function run at the end of your animation.

For example, if we take one of your animation codes:

    $(this).animate({
              'opacity': '1'
            }, {duration: 3000, done: function () {
                 //do something after animation
    }};

This technique can be used wherever jQuery animate is utilized. I've personally utilized it to manage nested animations within a slideshow layout and found it to work effectively. Hopefully, this aligns with what you were looking for!

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

eliminate the gap in the MUI Accordion when it is expanded

How can I prevent the Accordion MUI component from moving and applying top and bottom margins to summary elements in expanded mode? I added the following code to the summary element but it doesn't seem to be working. Any suggestions on how to fix this ...

Iteratively traverse the object to establish connections between parent and child elements

I've been working on creating a recursive function with some guidance I received here: looping through an object (tree) recursively The goal is to traverse the object 'o' and generate a new one where each key is associated with its parents ...

"Obtain a DOM element within an Angular directive by using the jQuery find method

When inspecting the DOM, I can see the element anchor tag present but cannot retrieve it using jquery.find(). The console returns a length of 0, preventing me from initializing angular xeditable on that element. angular.module('built.objects') ...

Accessing arrays using bracket notation

When working with TypeScript (or JavaScript), you have the option to access object properties using either dot notation or bracket notation: object.property object['property'] Let's explore a scenario using the latter method: const user = ...

"Utilizing mouseleave event to trigger an AJAX request in

Could an ajax request be initiated from a mouseleave event? My goal is to send the string 'Y' when the mouse exits the li element in order to update the database. Do you think this is feasible? (function(){ $('li#myId').mouseenter(f ...

Preventing the last letter from being cut off when using overflow:hidden

Check out this code snippet below... .panel { width:400px; overflow:hidden; background:lightgrey; font-size:30px; } <div class="panel"> This is a sample text to demonstrate the overflow property in CSS. We want to ensure that it do ...

AngularJS: Issue with Select Click Trigger Not Fired

I am puzzled as to why this code isn't working on Chrome but works perfectly fine on FireFox SelectModel selectModel: [ { value: "asc", htmlText : "A-Z", selected: "" }, ...

This JavaScript function assigns a value to an input field in a form, only to have the value vanish soon after

I'm attempting to create a dynamic database search using ajax with a form input field. Currently, I am able to choose a text from the suggested list and trigger the "livesearchSelect" event, which sets the value of the input field. However, the set va ...

What methods can be used to broaden configuration variables within VSCode using an extension?

I attempted to develop an extension for vscode that requires reading the pasteImage.parth variable from the ./vscode/settings.json file { "pasteImage.path": "${workspaceRoot}/assets/images" } In my attempt to retrieve the variable us ...

Verifying that the mapDispatchToProps functions have been triggered using ReactTestingLibrary

I am currently utilizing mapDispatchToProps to invoke a dispatch function that calls an API within the useEffect hook of my functional component. I am facing some challenges when attempting to write unit tests for this scenario using React Testing Library ...

Troubleshooting a JSON response issue in CodeIgniter

As a beginner in the codeigniter framework and json, I am attempting to retrieve data from the database upon user clicking on a specific URL. However, I'm encountering an error. This is my script: function fetchUserData(i) { if(i == 1) { ...

The gulp-stylus plugin fails to compile files due to an out-of-memory issue

Whenever I attempt to use the gulp-stylus plugin for compiling my stylus files, I encounter an issue. After running gulp stylus, gulp initiates the task "stylus," causing my CPU usage to spike up to 100%. Eventually, I receive this error message: FATAL ERR ...

Looking to change the date format from 24/05/2021 to 24/May/2021 using jQuery or JavaScript?

My client prefers not to use a date picker, but wants to be able to type dates directly into a textbox and have them automatically converted to the format 24/May/2021 as they leave the field. I am looking for a solution using either Javascript or jQuery. ...

Leveraging the power of $lookup and $mergeObjects in aggregation

I'm looking to join a collection. Previously, I used only lookup to get separated fields that are joined, but now I need the results similar to MySQL join. I have tried using $lookup and $mergeObjects for this action, but they are not working well. H ...

Adjust the placement of image when changing the size of the window

Is there a way to prevent an image with a fixed position from covering up page content when the browser window is resized? <div > <img id="img1" class="wrapperImage"></img> </div> <style type="text/css"> .wrapperImag ...

The issue with redirection not functioning is due to the specific sequence in which functions are executed

I'm currently working on a login page with the functionality to redirect users to a private panel if the login is successful and a token is stored in local storage. All functions are triggered onSubmit() of the form. This is an overview of my code: ...

Revamp the Design Layout of a Drag-and-Drop Tool

After experimenting with a drag and drop feature using jQuery, I discovered the following useful code snippet. Here's how it functions: $( "#sortable1, #sortable2" ).sortable({ connectWith: ".connectedSortable" }).disableSelection(); #so ...

JS: delay onClick function execution until a page refresh occurs

Currently, I am working on a WordPress site that involves a form submission process. Upon successful submission, a new post is created. After the user submits the form, I have implemented JavaScript to prompt them to share a tweet with dynamically prepopu ...

Any new techniques for generating HTML content dynamically?

Although I have experience writing HTML, JS, and CSS pages, my current methods for adding, changing, or updating elements on a page feel outdated. I often resort to using cumbersome solutions like creating new windows or manually manipulating DOM elements. ...

Submitting a form from a non-AngularJS application to an AngularJS app requires URL rewriting

I am facing a challenge with my AngularJS search application. The search box is located on a standard HTML page that is not part of the AngularJS framework. Here is how the input field looks: <form accept-charset="UTF-8" name="search" id="search" act ...