Starting an Angularjs CSS3 animation with JavaScript

I am currently exploring how to create a CSS3 animation in Angular.js.
Before starting the animation, I need to establish the initial CSS properties using Javascript.
Is there a way to kickstart an animation with Javascript and then smoothly transition it using CSS3?

Here's my scenario:
Upon clicking a div, a dialog should pop up. The dialog should initially match the size and position of the original div, then expand.

Currently, I can animate the dialog from a set position and size:

CSS:

.dialog {
    position: absolute;
    z-index: 10;
    width:600px;
    height:400px;
    margin-left: -300px;
    left:50%;
    margin-top: 50px;
}
.dialogHolder.ng-enter .dialog {
    transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1s;
    width:0;
    height:0;
    margin-left: 0px;
}
.dialogHolder.ng-enter-active .dialog {
    width:600px;
    height:400px;
    margin-left: -300px;
}

I aim to animate the dialog starting at the size of the clicked div. My current (non-functional) code snippet looks like this:

HTML:

<div ng-repeat="course in data.courses" ng-click="showDialog($event)">
    {{ course.cursus }}
</div>

<!-- Placeholder for blokDialogs -->
<div class="dialogHolder" ng-include="dialogTemplate.url">
    DIALOG WILL BE LOADED HERE
</div>

Javascript:

app.controller('blockController', function($scope) {

    $scope.showDialog = function(evt) {
        // get position and size of the course block
        $scope.dialogTemplate.clientRect = evt.target.getBoundingClientRect();

        // load the html to show the dialog
        $scope.dialogTemplate.url = 'partials/blokDialog.html';

        // WHAT SHOULD I DO HERE?
    };

});

// OR MAYBE SOMETHING LIKE THIS?
app.animation('.dialogHolder', function(){
    return {
        // ADJUST WIDTH, HEIGHT, TOP, LEFT OF .dialog SOMEHOW
    };
});

I prefer avoiding jQuery for a lighter page weight.

Best, Hendrik Jan

Answer №1

If you're looking to incorporate ng-animate into your project, check out the documentation at http://docs.angularjs.org/api/ngAnimate

When utilizing ng-repeat, you have the ability to animate elements as they enter, leave, and move within your repeater. The beauty of this feature is that no additional directive needs to be added in your HTML; simply define your CSS animations accordingly.

In your specific case, consider implementing something like the following:

.repeater.ng-enter, .repeater.ng-leave, .repeater.ng-move {
  -webkit-transition:0.5s linear all;
  transition:0.5s linear all;
}

.repeater.ng-enter { }
.repeater.ng-enter-active { }
.repeater.ng-leave { }        
.repeater.ng-leave-active { }
.repeater.ng-move { }        
.repeater.ng-move-active { }

Now, update your HTML code with the necessary modifications:

<div ng-repeat="..." class="repeater"/>

Answer №2

After much exploration, I finally discovered the perfect solution:


HTML:
I implemented an onClick handler and a designated spot for loading the dialog.

<!-- Clickable element to trigger the dialog -->
<div ng-repeat="course in data.courses"
     ng-click="showDialog($event, course)">
 {{ course.name }}
</div>

<!-- Placeholder for blokDialogs -->
<div class="dialogHolder"
     ng-include="dialogTemplate.url"
     onload="showDialogLoaded()">
</div>


HTML Template:
The styling for partials/blokDialog.html is set using ng-style.

<div ng-style="dialogTemplate.initialStyle">
...
</div>


Javascript:
The initial CSS is defined by the onClick handler prior to the animation commencement.

$scope.showDialog = function(evt, course) {

    // Load the dialog template
    $scope.dialogTemplate.url = 'partials/blokDialog.html';

    // set the css before the animation starts
    // get position and size of the course block
    var clientRect = evt.target.getBoundingClientRect();
    $scope.dialogTemplate.initialStyle = {
        left: clientRect.left + 'px',
        top: clientRect.top + 'px',
        width: clientRect.width + 'px',
        height: clientRect.height + 'px',
        backgroundColor: getComputedStyle(evt.target).backgroundColor
    };

};

The style must be removed post-animation initiation but pre-animation completion.
The actual animation begins upon completion of the onLoad handler. Removing the style in showDialogLoaded or any earlier point would occur prematurely.
To ensure proper timing, setTimeout is employed to guarantee that the style removal occurs after the animation has started.

$scope.showDialogLoaded = function() {
    // remove the style that we set in showDialog
    setTimeout(function(){
        $scope.dialogTemplate.initialStyle = {};
        // $apply is necessary as this function operates
        // outside the regular Angular flow, prompting Angular
        // to perform a dirty check
        $scope.$apply();
    }, 0);
};

This insight may prove beneficial to others seeking a similar solution.
Best Regards,
HJ

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

What is the best way to toggle the visibility of select tags using another select tag?

I have a piece of code with one parent select tag containing two options: apples and butter. Each option has a value of 1 and 2 respectively. When I select apples, another select tag should appear, and vice versa. However, my issue is that multiple select ...

Tips for formatting HTML to showcase two data cards when printing a page

My XML data input document can be neatly transformed into printable data cards, whether it's 2 to a page, 4 to a page, 9 to a page, or any other configuration. What is the most effective method for styling the data to fit the printing layout? How can ...

Struggling to customize the style of bootstrap components

Struggling to get my custom css to take precedence over Bootstrap4 components in my Django project. I'm a beginner in front-end development and I'm hoping to articulate my question clearly. Note: This is an HTML sheet within a Django project. My ...

Prepending a string to the key of a JSON object using JavaScript

Is there a way to add 'd:' before the key of a JSON object? Here is the JSON data: "data": { "aa": "value", "ab": "value" } The expected result should look like this: "d:data": ...

I encountered a SyntaxError that reads "Unexpected token instanceof" while using the Chrome Javascript console

I find it quite surprising that the code below, when entered into the Chrome JavaScript console: {} instanceof Object leads to the error message displayed below: Uncaught SyntaxError: Unexpected token instanceof Could someone kindly explain why this ...

How can I get my HTML DIVs to automatically move downward instead of upwards?

I'm currently developing a chat script that includes the feature to minimize specific chats, but I've encountered an issue with making the header of the div push down. Despite researching extensively, I haven't been able to find a solution t ...

Implementing ordering and limiting of elements in NestJS TypeORM relations

I am new to typeorm and relationships. I am currently facing some challenges and feeling a bit confused. I have a question regarding sorting relations in typeorm by id or createdDate without explicitly mapping them and limiting the number of elements. Here ...

React Hooks findByID method is throwing an error stating that it cannot read the property 'params' because it is undefined

As I dive into learning React hooks, I'm realizing that it's crucial to stay up-to-date with the latest trends in web development. Despite hours of research and tinkering around, I can't seem to wrap my head around some key concepts. The fac ...

Is it possible to modify the color of a division row using an onchange event in JQuery?

I am facing a requirement to dynamically change the color of rows based on the dropdown onchange value. The rows are structured in divisions, which were previously tables. There are two main divisions with rows that need to be updated based on dropdown sel ...

How can you prevent the 'Script not responding' error when using Reverse AJAX / Comet?

My worker thread is responsible for sending requests to the server using XMLHttpRequest. The request is directed to a php file which checks the integrity of client information. If the client requires new data, it is sent. Otherwise, the server continuously ...

Using three.js to generate a cube around a tubular structure

Could you please provide the URL for tube geometry: 3D tube with 200 points of data passed in JSON format. I am interested in dynamically creating a transparent cube around the tube geometry to cover the entire structure inside it. This would make the sce ...

JavaScript loop that removes the first matching element in an array

My array of Exclusions is structured as shown below: Exclusions: [ID:"233242", Loc:"West", ID:"322234" , Loc:"South"] Within my Object, I have a nested array of objects that resembles: Schools : [ O: [ ID:"233242" ] , 1:[ ID:"233242"] , 2: [ID :"954944" ...

Issue with Angularjs: NG-repeat and filter not functioning correctly on array

After spending the last 3 hours searching on Google and Stack Overflow, I thought this would be easy, but I'm still stuck. I have a simple ng-repeat where I need to display everything from data2 that matches the unique ID in my data1's ref_id co ...

The functionality of the Youtube API is not compatible with a dynamically generated array of objects

Encountering an unusual problem with the Youtube API... I am in the process of developing a script that identifies all Youtube videos on a webpage and then replaces them using the Youtube API. This approach enables me to monitor API events like video compl ...

Implementing ng-clip AngularJS directive to allow for numerous "copy to clipboard" buttons for various text items

I experimented with this sample: <a href='http://plnkr.co/xwV5Yn'>http://plnkr.co/xwV5Yn</a> However, I noticed that it only functions correctly for the initial element, regardless of which copy button is clicked. ...

Is there a way to determine if a line has been automatically wrapped within a textarea element?

Is it possible to detect when text is wrapped onto the next line in a textarea after becoming wider than the area? ...

Guide on integrating an event in Angular 4 to an HTML element inserted using an external library

Recently, I integrated the jQuery wizard library into my project to streamline user interactions. One of the key features it provides is automatically adding next and back buttons to guide users through the wizard process. You can find more information abo ...

Tips for locating an element without a class assigned

I am currently utilizing the webdriverIO framework for my script, specifically working with a calendar where I need to extract only the days from the current month. Below is an excerpt of the HTML code: <tr class="daysrow"> <td class="day w ...

Maintain uniform height of divs while adjusting image size without altering padding

My challenge lies in creating a layout of images in columns with consistent padding between them. The ultimate goal is to ensure that the images align at the bottom, regardless of screen size variations as depicted in this image: The problem arises when t ...

When using the `display: table-cell` property on a div element, it does not automatically respect

How can I restrict the width of columns by defining a width attribute on the div.dcolumn DOM element to preserve the layout with overflowing cells? I want the content of any overflowing cell (like the 9px column) to be hidden while maintaining the specifie ...