Sunday, November 4, 2018

jquery - How can I run a directive after the dom has finished rendering?




I've got a seemingly simple problem with no apparent (by reading the Angular JS docs) solution.



I have got an Angular JS directive that does some calculations based on other DOM elements' height to define the height of a container in the DOM.



Something similar to this is going on inside the directive:



return function(scope, element, attrs) {
$('.main').height( $('.site-header').height() - $('.site-footer').height() );
}



The issue is that when the directive runs, $('site-header') cannot be found, returning an empty array instead of the jQuery wrapped DOM element I need.



Is there a callback that I can use within my directive that only runs after the DOM has been loaded and I can access other DOM elements via the normal jQuery selector style queries?


Answer



It depends on how your $('site-header') is constructed.



You can try to use $timeout with 0 delay. Something like:




return function(scope, element, attrs) {
$timeout(function(){
$('.main').height( $('.site-header').height() - $('.site-footer').height() );
});
}


Explanations how it works: one, two.



Don't forget to inject $timeout in your directive:




.directive('sticky', function($timeout)

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...