Allenph
Allenph

Reputation: 2015

Applying jQuery animation to element in view dynamically loaded by Angular JS on load?

I have a single page application that uses Angular JS routing. On an element in one of the dynamically loaded views, I would like to apply a jQuery animation. Simply including a jQuery script at the bottom of the page is not sufficient because it should theoretically only be called once.

However, that being the case I can't even get it to call the first time. I have the following code...

jQuery:

$("#main-content-overlay").fadeIn().animate({top:65}, 500);

HTML:

<img src="images/home/main-content-background.jpg" id="main-content" />
<img src="images/home/main-content-overlay.png" id="main-content-overlay" />

Again, the aforementioned HTML is part of a view that is loaded dynamically by Angular. I would like my animation to be applied every time the route changes, but I can't even get the animation to work on the first load.

Upvotes: 0

Views: 233

Answers (3)

Skam
Skam

Reputation: 7798

Well first of all using Angular and jQuery together is bad practice but here's a link that might be useful concerning How to use jQuery in AngularJS

var myEl = angular.element(document.querySelector( '#main-content-overlay'));   
myEl.fadeIn().animate({top:65}, 500);

It might be a little much but it gives you a better understanding of what is actually happening.

Upvotes: 0

Allenph
Allenph

Reputation: 2015

Perhaps I wasn't specific enough in my question, but I have since discovered the answer. Since I wasn't intending to include this part of the view with the animation in the whole site, I simply attached my jQuery to a controller who's scope covered my images. I then created a function within the scope of that controller, and called that function.

My code in the associated controller:

this.animateOverlay = function() {
    $("#main-content-overlay").fadeIn({queue: false, duration: 1000}).animate({top: "+=65px"}, 500);
};
this.animateOverlay();

Upvotes: 0

Alejandro Ocampo
Alejandro Ocampo

Reputation: 266

I am not sure where are you trying to call the animation stuff. But, since you're saying you cannot even make it to work for the first time then my guess is that you don't know where to put your code. Try:

$scope.$on('$locationChangeStart', function(event) {
  // Do something here (like calling your animation)
});

You can see a discussion here that might provide further useful information https://github.com/angular/angular.js/issues/2109

Upvotes: 2

Related Questions