user4012084
user4012084

Reputation:

Sticky header slide down effect

$(window).scroll(function(){
         var sticky = $('.top-menu'),
         scroll = $(window).scrollTop();

        if (scroll >= 200){
            sticky.addClass('fixed');
        }else{
            sticky.removeClass('fixed');
        }
    });

Fixed css

.fixed{
    position: fixed;
    background: red;
    z-index: 1;
}

It works fine, but i want a 'slide down of the top effect' can i do that?

Thanks!!

Upvotes: 0

Views: 8438

Answers (4)

Gerard Simpson
Gerard Simpson

Reputation: 2126

You could try adding code like this so you don't have to specify a height in pixels:

var sticky = document.querySelector('.sticky');
var origOffsetY = sticky.offsetTop;

function onScroll(e) {
  window.scrollY >= origOffsetY ? sticky.classList.add('fixed') :
                                  sticky.classList.remove('fixed');
}

document.addEventListener('scroll', onScroll);

Upvotes: 0

vijayP
vijayP

Reputation: 11502

For smooth slide down animation you can try following things:
JS Code:

$(window).scroll(function(){
         var sticky = $('.top-menu'),
         scroll = $(window).scrollTop();
        if (scroll >= 200){
            sticky.addClass('fixed');
            sticky.slideDown(1000);
        }else{
            sticky.removeClass('fixed');
            sticky.removeAttr("style"); //slideDown adds the style="block" which needs to be removed so that next time slideDown will work
        }
    });

CSS Code:

.fixed{
    position: fixed;
    background: red;
    z-index: 1;
    display:none;
}

Here logic is; to add 'fixed' class after 200px scroll. At this moment sticky will be display:none via added CSS class. Then slide it down to make it visible. If user scrolls up and goes below 200px then remove fixed class and remove style attribute added to sticky via slideDown() function. Hope this will help. I tried it and its working perfectly like www.walmart.com

Upvotes: 4

Adjit
Adjit

Reputation: 10305

You should look into CSS transition and transform properties.

  • Transition will control how quickly an object animates.
  • Transform will control the transformation of the object. (i.e. height from 0 - 100px)

A good resource for learning about CSS3 is here and you should just run through the tutorial.

Upvotes: 1

Amit Singh
Amit Singh

Reputation: 2275

I am not much into css stuff but still I guess this might work:

       if (scroll >= 200){
             sticky.slideDown();
            sticky.addClass('fixed');
        }else{

            sticky.slideUp();
            sticky.removeClass('fixed');
        }

Upvotes: 0

Related Questions