75

I'm trying to use ng-animate to get a behavior similar to JQuery's slideUp() and slideDown(). Only I'd rather use ng-show

I'm looking at the ng-animate tutorial here - http://www.yearofmoo.com/2013/04/animation-in-angularjs.html,

and I can reproduce the fade in/out effect in the example provided.

How could I change the css to get slide up/down behaviour? Also, if possible, it's better that the css doesn't know about the component height in pixels. That way I can reuse the css for different elements.

5
  • 1
    I do not think you will be able to get ng-show to handle animations. That is not its intended use. That is what ng-animate is for. Why do you want to use ng-show specifically? May 21, 2013 at 18:56
  • 1
    Thanks Jonathan. I think you're mistaken. The given example does exactly that: a combination of ng-show and ng-animate (look for "Animating ngShow & ngHide"). Anyway, what I want is simply an effect to show/hide a div sliding up and down. May 21, 2013 at 19:07
  • My mistake, I have not made use of ng-animate. It looks as though in they work in conjunction with each other. May 21, 2013 at 19:19
  • You could try to use the line-height css attribute, from 0 to 100%. Sometimes it's works... Post your fiddle than we can help you better. If you find a good way to do this, please, send me it, to put this sample at my site: AngularJS Ng-Animate May 24, 2013 at 16:35
  • Check this out nganimate.org
    – hasser
    Jun 21, 2013 at 17:25

8 Answers 8

87

I've written an Angular directive that does slideToggle() without jQuery.

https://github.com/EricWVGG/AngularSlideables

9
  • 1
    This looks exactly like what I wanted. Thanks! Nov 2, 2013 at 10:49
  • 3
    @BastienSander Angular provides a subset of some of Jquery's methods if you don't include jquery before you include Angular, api docs for that here: docs.angularjs.org/api/ng/function/angular.element .css and .bind are provided there (which is used on the "element" variable). The easing and duration properties aren't being used on element, so they're not referencing the Jquery methods of the same name, but are properties passed in on the HTML attributes (attrs object).
    – Jay Klehr
    Jun 11, 2014 at 20:33
  • 2
    Most minimal "accordion" style slider I have ever seen! Thank you! We modified it a little bit to remove IDs and class stuff that we saw as unnecessary as we could find the elements without IDs: plnkr.co/edit/11NIZqB3G3KYKI0OChGA?p=preview
    – Pylinux
    Dec 9, 2014 at 8:04
  • 1
    The id's are kinda needed (if you want to dropdown an element that is somewhere else) so i made a slightly modification fixing some bugs and now it works like a charm. plnkr.co/edit/XdRjap3TPFEC9180yq9k?p=preview
    – Marcio
    Apr 7, 2015 at 7:27
  • 7
    I know we've plunked this to death, but I like tying the visibility to variables. Also, this solution doesn't allow for embedded sliders. I've created a fiddle that does both: jsfiddle.net/rh7z7w0a/2
    – jbodily
    Mar 25, 2016 at 1:05
40

This is actually pretty easy to do. All you have to do is change the css.

Here's a fiddle with a very simple fade animation: http://jsfiddle.net/elthrasher/sNpjH/

To make it into a sliding animation, I first had to put my element in a box (that's the slide-container), then I added another element to replace the one that was leaving, just because I thought it would look nice. Take it out and the example will still work.

I changed the animation css from 'fade' to 'slide' but please note that these are the names I gave it. I could have written slide animation css named 'fade' or anything else for that matter.

The important part is what's in the css. Here's the original 'fade' css:

.fade-hide, .fade-show {
    -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
    -moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
    -o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
    transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
}
.fade-hide {
    opacity:1;
}
.fade-hide.fade-hide-active {
    opacity:0;
}
.fade-show {
    opacity:0;
}
.fade-show.fade-show-active {
    opacity:1;
}

This code changes the opacity of the element from 0 (completely transparent) to 1 (completely opaque) and back again. The solution is to leave opacity alone and instead change the top (or left, if you want to move left-right).

.slide-hide, .slide-show {
    -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
    -moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
    -o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
    transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
}
.slide-hide {
    position: relative;
    top: 0;
}
.slide-hide.slide-hide-active {
    position: absolute;
    top: -100px;
}
.slide-show {
    position: absolute;
    top: 100px;
}
.slide-show.slide-show-active {
    position: relative;
    top: 0px;
}

I'm also changing from relative to absolute positioning so only one of the elements takes up space in the container at a time.

Here's the finished product: http://jsfiddle.net/elthrasher/Uz2Dk/. Hope this helps!

4
  • This was very helpful. I'm trying to figure out why the 'hide' transition is so sudden in your fiddle though, @elthrasher Apr 1, 2014 at 0:13
  • 1
    @ericpeters0n - it's because of that 0.5s at the end of the transition line. That's the amount of time it'll take, half a second in this case. You may set that to whatever you like. Try 5s or 10s.
    – elthrasher
    Apr 4, 2014 at 0:36
  • 2
    The behavior is kind of odd. Sometimes the text appears from the top and sometimes from the bottom.
    – nikk wong
    Jul 10, 2015 at 1:04
  • I know it's an old answer but if anybody wants to give this a try I'd like to clarify that using ng-hide="hidden == false" is redundant, if the hidden variable is already a boolean then the operator is not needed at all.
    – GMaiolo
    Jan 18, 2016 at 0:10
17

update for Angular 1.2+ (v1.2.6 at the time of this post):

.stuff-to-show {
  position: relative;
  height: 100px;
  -webkit-transition: top linear 1.5s;
  transition: top linear 1.5s;
  top: 0;
}
.stuff-to-show.ng-hide {
  top: -100px;
}
.stuff-to-show.ng-hide-add,
.stuff-to-show.ng-hide-remove {
  display: block!important;
}

(plunker)

2
  • 16
    Don't animate top position with css, it is very slow and takes up a lot of memory. Use translate instead. May 2, 2014 at 9:10
  • 1
    Also works on Angular 1.4. Tested and it works like a charm! Nov 25, 2015 at 16:23
16

This can actually be done in CSS and very minimal JS just by adding a CSS class (don't set styles directly in JS!) with e.g. a ng-clickevent. The principle is that one can't animate height: 0; to height: auto; but this can be tricked by animating the max-height property. The container will expand to it's "auto-height" value when .foo-open is set - no need for fixed height or positioning.

.foo {
    max-height: 0;
}

.foo--open {
    max-height: 1000px; /* some arbitrary big value */
    transition: ...
}

see this fiddle by the excellent Lea Verou

As a concern raised in the comments, note that while this animation works perfectly with linear easing, any exponential easing will produce a behaviour different from what could be expected - due to the fact that the animated property is max-height and not height itself; specifically, only the height fraction of the easing curve of max-height will be displayed.

12
  • 3
    That's bad cause the animation speed changes depending on max-height.
    – RushPL
    Apr 2, 2015 at 19:41
  • why is it bad? If you are having issues with the animation speed, simply set the transition duration to a reasonable value based on your max-height. It's exactly how transitions are supposed to work. This method actually has the benefit that the slideup/down speed remains constant regardless of the height
    – Luca
    Apr 7, 2015 at 10:54
  • 1
    @RushPL this is a fair explanation - it makes sense now.
    – Luca
    Apr 10, 2015 at 10:43
  • 1
    I have to vote on this approach. Simple, as well as using ngAnimate framework.
    – windmaomao
    Jun 23, 2015 at 16:41
  • 1
    This should be marked the answer as I was lead here in search of a way to cheat height:auto like the original poster was Apr 5, 2016 at 2:27
8

I ended up abandoning the code for my other answer to this question and going with this answer instead.

I believe the best way to do this is to not use ng-show and ng-animate at all.

/* Executes jQuery slideDown and slideUp based on value of toggle-slidedown 
   attribute.  Set duration using slidedown-duration attribute.  Add the 
   toggle-required attribute to all contained form controls which are
   input, select, or textarea.  Defaults to hidden (up) if not specified
   in slidedown-init attribute.  */
fboApp.directive('toggleSlidedown', function(){
    return {
        restrict: 'A',
        link: function (scope, elem, attrs, ctrl) {
            if ('down' == attrs.slidedownInit){
                elem.css('display', '');
            } else {
                elem.css('display', 'none');
            }
            scope.$watch(attrs.toggleSlidedown, function (val) {
                var duration = _.isUndefined(attrs.slidedownDuration) ? 150 : attrs.slidedownDuration;
                if (val) {
                    elem.slideDown(duration);
                } else {
                    elem.slideUp(duration);
                }
            });
        }
    }
});
4
  • Thanks for providing the newer solution. Out of curiosity (as I didn't find any particular issues with piggybacking off ng-hide/ng-show) ... what was the problem with that approach?
    – zai chang
    Aug 25, 2015 at 11:19
  • You should have modified your previous answer instead of creating a new one (imagine the mess if everybody creates a new answer each time they want to modify something...)
    – tanguy_k
    Oct 20, 2015 at 11:10
  • 2
    @tanguy_k I think there might be a way to correct the first answer, and possibly both approaches are valid. I guess I was hoping someone would critique my first answer and tell me why it occasionally fails. I think there may be multiple equally good answers to this question. Oct 20, 2015 at 22:13
  • 1
    Problem with editing the original answer is that if the questioner marked that as 'correct' and then you make significant mods... that seems like a bad idea as well. Dec 9, 2016 at 14:44
6

This class-based javascript animation works in AngularJS 1.2 (and 1.4 tested)

Edit: I ended up abandoning this code and went a completely different direction. I like my other answer much better. This answer will give you some problems in certain situations.

myApp.animation('.ng-show-toggle-slidedown', function(){
  return {
    beforeAddClass : function(element, className, done){
        if (className == 'ng-hide'){
            $(element).slideUp({duration: 400}, done);
        } else {done();}
    },
    beforeRemoveClass :  function(element, className, done){
        if (className == 'ng-hide'){
            $(element).css({display:'none'});
            $(element).slideDown({duration: 400}, done);
        } else {done();}
    }
}

});

Simply add the .ng-hide-toggle-slidedown class to the container element, and the jQuery slide down behavior will be implemented based on the ng-hide class.

You must include the $(element).css({display:'none'}) line in the beforeRemoveClass method because jQuery will not execute a slideDown unless the element is in a state of display: none prior to starting the jQuery animation. AngularJS uses the CSS

.ng-hide:not(.ng-hide-animate) {
    display: none !important;
}

to hide the element. jQuery is not aware of this state, and jQuery will need the display:none prior to the first slide down animation.

The AngularJS animation will add the .ng-hide-animate and .ng-animate classes while the animation is occuring.

4
  • This works perfectly for me while I wasn't able to get the other answers to work well for me. Up-voted!
    – zai chang
    Aug 20, 2015 at 15:11
  • @zaichang I ended up abandoning this code and went a completely different direction. I like my other answer much better. This answer will give you some problems in certain situations. Aug 20, 2015 at 19:06
  • @steampowered This will/can not work with ngIf. But I see too that it is not working in some occasions even when you use ngShow. E.g. it seems that it doesn't work when I use it inside a modal created with UI-Bootstrap. This is weird. When did it fail for you?
    – NoOne
    Apr 2, 2016 at 21:59
  • the display:none thing did the trick... using ng-animate/ng-show with enter/leave functions and jquery UI toggle effects. Nothign worked right until I added display:none to the element... thanks! Dec 9, 2016 at 14:42
3

You should use Javascript animations for this - it is not possible in pure CSS, because you can't know the height of any element. Follow the instructions it has for you about javascript animation implementation, and copy slideUp and slideDown from jQuery's source.

0

What's wrong with actually using ng-animate for ng-show as you mentioned?

<script src="lib/angulr.js"></script>
<script src="lib/angulr_animate.js"></script>
<script>
    var app=angular.module('ang_app', ['ngAnimate']);
    app.controller('ang_control01_main', function($scope) {

    });
</script>
<style>
    #myDiv {
        transition: .5s;
        background-color: lightblue;
        height: 100px;
    }
    #myDiv.ng-hide {
        height: 0;
    }
</style>
<body ng-app="ang_app" ng-controller="ang_control01_main">
    <input type="checkbox" ng-model="myCheck">
    <div id="myDiv" ng-show="myCheck"></div>
</body>
1
  • 1
    It works if you can hard code the height in your CSS, but that is often not possible.
    – Waruyama
    Jul 26, 2016 at 9:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.