David Jones
David Jones

Reputation: 25

How to animate sticky header?

I have a sticky header which is fixed on scroll using jQuery when reaching a height of 160.

$(window).scroll(function()
{

    if( $(window).scrollTop() > 160)
{

        $('.dark-menu').addClass('stickyNav');
        $('header').addClass('mainHeaderFixed');
        $(".menu-second-menu-container").hide();
        $(".menu-first-menu-container").addClass('new-end');
        $("a.main-logo").hide();
        $("a.small-logo").show();
        $(".bp-phone").addClass("stickyNumber");
        $("img.telephoneIconHeader").addClass("stickyImg");
        $("a.topHeaderMailto").addClass("stickyaa");        
}
else
{
        $('.dark-menu').removeClass('stickyNav');
        $("a.topHeaderMailto").removeClass("stickyaa");
        $('header').removeClass('mainHeaderFixed');
        $(".menu-second-menu-container").show();
        $(".menu-first-menu-container").removeClass('new-end');
        $("a.main-logo").show();
        $("a.small-logo").hide();
        $(".bp-phone").removeClass("stickyNumber");
        $("img.telephoneIconHeader").removeClass("stickyImg");
} 
});

This is fine for showing / hiding elements, but I want the whole sticky nav and the backbar to animate on scroll.

I have tried to apply CSS on the header sections:

    -webkit-transition: height 5s;
    -moz-transition: height 5s;
    transition: height 5s;

But this is not working. What can I do to make this animate on scroll?

Here is my site:

http://insurancefocus.bemediadev.com.au/

Here is what I would like to achieve:

https://codepen.io/malZiiirA/pen/cbfED

Upvotes: 0

Views: 1851

Answers (1)

Tom M
Tom M

Reputation: 2894

Edit

The header of the pen you posted is always fixed, not sticky. If you want this, you need to give your .main position: fixed from the start and just change the height of the elements.

The transition has no effect on your header because it does not have a set height. It just gets recalculated when you swap out the two logo versions.

For more information on this, see css3 height transition not working or if you don't want to specify a height, see How can I transition height: 0; to height: auto; using CSS?

Old

Setting a transition on height will only show effect if the height of the element actually changes. In your case, the height remains the same. Try using the following CSS to change the height of your element and you will see the transition.

.main {
    height: 100px;

    -webkit-transition: height 5s;
    -moz-transition: height 5s;
    transition: height 5s;
}

.main.mainHeaderFixed {
    height: 160px;
}

Upvotes: 1

Related Questions