Dynamically making an element fixed (header) in fullpage.js

Prabu picture Prabu · Jan 16, 2015 · Viewed 7.5k times · Source

I'm building a page in fullpage.js. On the first slide is an image that consumes 90% of the height of the viewport. The other 10% is a navigation bar at the below the image. The image below demonstrates it.

enter image description here

As I scroll to the next slide, I want the navigation bar to become a fixed header for the remainder of the slides.

I tried making the element fixed once it's offset().top value is 0 against $(window).top() using jQuery. This did not work for me.

$(window).scroll(function () {
    var nav = $('#nav');

    var eTop = nav.offset().top;
    if ((eTop - $(window).scrollTop()) == 0) {
        nav.addClass('fixed');
    }
    else {
        nav.removeClass('fixed');
    }
});

Is this possible and how do I achieve it?

Answer

Alvaro picture Alvaro · Jan 17, 2015

If you are using the default option css3:true, then this will do the trick:

$('#fullpage').fullpage({
    sectionsColor: ['yellow', 'orange', '#C0C0C0', '#ADD8E6'],
    onLeave: function(index, nextIndex, direction){
        //leaving 1st section
        if(index == 1){
           $('.header').addClass('fixed');
        }
        //back to the 1st section
        if(nextIndex == 1){
            $('.header').removeClass('fixed');
        }
    }      
});

And you will need this CSS for the header element:

.header{
    -webkit-transition: all 0.7s ease;  
    -moz-transition: all 0.7s ease;  
      -o-transition: all 0.7s ease; 
         transition: all 0.7s ease; 

    position:absolute;
    top:100%;
    margin-top: -100px;
    left:0;
    background:#000;
    width:100%;
    color: #fff;
    height: 100px;
    z-index:999;
}
.header.fixed{
    bottom:auto;
    top:0;
    margin-top: 0;
}

You can of course, change the height and so on.

Take into account that I've placed the fixed element outside the plugin's wrapper. This way I will avoid problems with the translate3d property used by the plugin:

<div class="header">Header</div>

<div id="fullpage">
    <div class="section">...</div>
    <div class="section">...</div>
   ...
</div>

See a demo

Update:

If you are using scrollBar:true, then use the following CSS instead of the previous one:

.section {
    text-align:center;
}
.header{
    -webkit-transition: all 0.7s cubic-bezier(0.895, 0.030, 0.685, 0.220);  
    -moz-transition: all 0.7s cubic-bezier(0.895, 0.030, 0.685, 0.220);  
      -o-transition: all 0.7s cubic-bezier(0.895, 0.030, 0.685, 0.220); 
         transition: all 0.7s cubic-bezier(0.895, 0.030, 0.685, 0.220); 
    position:fixed;
    top:100%;
    margin-top: -100px;
    left:0;
    background:#000;
    width:100%;
    color: #fff;
    height: 100px;
    z-index:999;
}
.header.fixed{
    bottom:auto;
    top:0;
    margin-top: 0;
    position:fixed;
}

See demo