Assigning a CSS class during the $routeChangeStart event does not activate the animation, unless it is placed within a setTimeout function

Just dipping my toes into Angular, so feel free to correct me if I'm way off base here.

I've been working on animating the clamps on both sides of my website to slide in upon the initial page load. You can check out the live version at:

Currently, it's functioning as intended (hooray). However, I'm not entirely satisfied with the method I've employed. Here's the relevant code:

Within my controller, I've set up an event listener for $routeChangeStart, and upon the first instance, I execute:

setTimeout(function() {
    angular.element(document.querySelector('.robotarmleft')).addClass('animate-in');
    angular.element(document.querySelector('.robotarmright')).addClass('animate-in');
}, 0);

This snippet selects the two clamp elements and adds the class animate-in, which comes with the following CSS styling:

.robotarm {
    margin-left: -2048px;
    margin-right: -2048px;
}

.animate-in {
    -webkit-transition: all 2s ease;
    -moz-transition: all 2s ease;
    -o-transition: all 2s ease;
    transition: all 2s ease;

    margin-left: -1300px;
    margin-right: -1300px;
}

In theory, this setup should render the arms off-screen and then smoothly animate them into view.

If I try adding the animation classes directly without the setTimeout, the animation doesn't trigger at all.

Why does the addClass need to be inside a setTimeout function to work properly? Should I kickstart the animation with some other event like onPageLoadTheFirstTime specific to Angular? Mainly seeking guidance on the recommended approach rather than opting for another quick fix.

Appreciate any insights you can offer!

Answer №1

Consider using $timeout instead of setTimeout() to ensure you stay within the angular digest cycle.

The reason for using a timeout is likely because it needs to be executed after the DOM has rendered, ensuring that your angular.element(..) calls do not return []. You may need to listen for an event that occurs after the DOM has been fully rendered, such as ui-router's $viewContentLoaded event.

Using $timeout to delay code and trigger a digest cycle is a common workaround for many issues, as demonstrated in this example.

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

Identify whether a specific Instagram post is a video by utilizing Python with selenium

Good day, After reviewing the content on this post: () I managed to extract specific data using the following code: likes = driver.execute_script('''return document.getElementsByClassName('Nm9Fw')[0].lastElementChild.getElement ...

How to organize initial, exit, and layout animations in Framer Motion (React) tutorial?

Currently, I am utilizing framer-motion library for animating a change in grid columns. This is the objective: Within the grid container (#db-wrapper), there are nine buttons arranged. https://i.stack.imgur.com/61pQqm.png When the user switches to the ...

Angular 8 experiencing unexpected collision issues

Currently, I am utilizing Angular 8 with "typescript": "~3.5.3". My objective is to handle the undefined collision in my code. const { testLocation } = this.ngr.getState(); this.step2 = testLocation && testLocation.step2 ? testLocat ...

Incorporating live text into a tag while arranging items by price in both ascending and descending order

I recently added a button to my online shop that allows users to sort products by price, even though I don't fully understand the underlying JavaScript code. I want to enhance this button by updating the text to indicate whether the sorting order is ...

Can JavaScript be used to retrieve time information from a central location?

In the process of developing a PhoneGap application, I am restricted to using only HTML, CSS, and JavaScript. I am seeking guidance on how to retrieve time information from a centralized server using strictly JavaScript. Is it possible to achieve this by ...

How to dynamically load bootstrap-multiselect within a loop in a vueJs application

I am attempting to dynamically load bootstrap-multiselect in a loop using VueJs. My desired implementation looks something like this: <div class="col-xs-6 col-sm-4 mb-1" v-for="params in param"> <select class="mult" multiple="multiple"> ...

Version 2: "In case of an empty input field, the submit button should be

After experimenting with two different codes on my websites, I encountered an issue. The first code looked like this: $(document).ready(function(){ $('.sendButton').attr('disabled', true); $('#message').keyup(function ...

Creating a nested function and utilizing the return statement in JavaScript

I am facing an issue with my custom function that contains an ajax call. I need to retrieve a variable from the ajax function within my custom function, but I'm unable to do so. Why is this happening? Possible solution 1: <script> function ...

Switch up the blogs displayed depending on the category chosen using React

I seem to have hit a roadblock with my current issue. My challenge involves organizing and displaying blog posts according to their categories: const Posts = ({ state }) => { const data = state.source.get(state.router.link); const postsPerCategory ...

Stunning CRUD tables in AngularJS featuring dynamic jQuery pop-up windows

Hello, I have developed a small CRUD application using AngularJS and encountered a minor issue. The application is functioning correctly overall, but there is a problem: when adding a new record and then attempting to edit it, the pop-up box I created does ...

Connecting Ionic/Angular directives to scrollbars

I'm having an issue with my scrolling div: <div class="list"> <div class="item" ng-repeat="post in posts"> <img src="post.img" is-visible/> </div> </div> and I've implemented this directive: angular.elemen ...

How can I assign a default value for a multiple select dropdown list in AngularJS?

I am currently facing an issue with my multiselect dropdown. The code for the dropdown is as follows: <select id="year" multiple ng-model="type" ng-disabled="!type1" > <option value="all" selected>all</option>; <option value= ...

Safari is encountering a 'Invalid Date' error in Javascript

Help me solve this issue with my script: var date = new Date("19871104071535".replace( /^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/, '$4:$5:$6 $2/$3/$1' )); alert(date); The script run ...

Step-by-step guide on creating a login functionality in Node using the Mean.io stack

I'm currently working on a web app using the MEAN.io stack. I have completed the frontend part with HTML, CSS, and AngularJS along with some logic. Now, I am looking to implement server-side login functionality, but I'm unsure where to begin sinc ...

Unusual behavior being exhibited by the background in an HTML5 canvas

I have an 800 by 100 image for the background and I'm trying to extract sections from it (like a sprite sheet) in order to create a background. I believe this method is efficient and allows me to experiment and learn how to generate backgrounds in the ...

Display the list in a grid format with 4 columns and x number of rows by utilizing Angular and Bootstrap

I need to display a list of values [1,2,3,4,5,6,7,8,9,10] as a bootstrap grid (class="col-x") using AngularJS. My goal is to create a grid with 4 columns and 3 rows from this list. Can you suggest the most efficient method to achieve this? ...

How can the name of an element be passed as an argument to a function called by that element within a Vue component?

I'm currently developing an interactive SVG map inspired by the one found on the CDC page. In my SVG map component, I have implemented multiple path elements that each contain a unique name attribute representing the corresponding state. Additionally, ...

Notify users with a prompt when a modal or popup is closed on Google Chrome extensions

I have developed a Google Chrome extension for setting timers and receiving alerts. Currently, the alert only goes off when the extension is open, but I want it to fire even when the extension is closed. This extension currently requires the window to be ...

Empty form field when submitting form using ajax in C# MVC

I am encountering an issue while attempting to store form data in a database using $.ajax. The problem lies in the fact that upon submitting the form, the username is being saved as null, whereas the email and password are correctly stored. function Sav ...

Is it possible to stack one Canvas on top of another?

Right now, I am engaged in a process that involves: creating a canvas and attaching it to a division applying a background image through CSS to that canvas. drawing a hex grid on the canvas placing PNGs on the canvas. animating those PNGs to show "movem ...