How to implement jquery like slideDown() in zepto

Goje87 picture Goje87 · Sep 5, 2012 · Viewed 8.5k times · Source

I am using zepto library for my mobile web site. I have recently learnt that zepto does not have slideDown() plugin like jquery. I would like to implement the same for zepto.

I have tried one on jsfiddle (http://jsfiddle.net/goje87/keHMp/1/). Here it does not animate while showing the element. It just flashes down. How do I bring in the animation?

PS: I cannot provide a fixed height because I would be applying this plugin to the elements whose height property would not be known.

Thanks in advace!!

Answer

Danil Speransky picture Danil Speransky · Sep 5, 2012

Demo: http://jsfiddle.net/6zkSX/5

JavaScript:

(function ($) {
  $.fn.slideDown = function (duration) {    
    // get old position to restore it then
    var position = this.css('position');

    // show element if it is hidden (it is needed if display is none)
    this.show();

    // place it so it displays as usually but hidden
    this.css({
      position: 'absolute',
      visibility: 'hidden'
    });

    // get naturally height
    var height = this.height();

    // set initial css for animation
    this.css({
      position: position,
      visibility: 'visible',
      overflow: 'hidden',
      height: 0
    });

    // animate to gotten height
    this.animate({
      height: height
    }, duration);
  };
})(Zepto);

$(function () {
  $('.slide-trigger').on('click', function () {
    $('.slide').slideDown(2000);
  });
});​
​