TristanD27
TristanD27

Reputation: 89

Nav bar appearing and disappearing on scroll

So I am trying to make a nav bar which is hidden when you first load the page and displays when you scroll down to the second section, I have got it working but when you scroll up and down within the home section, the nav bar keeps appearing and disappearing again when it should stay out of sight.

Live Demo: http://zimxtrial.ukbigbuy.com/

JS:

<script type="text/javascript">
jQuery(document).ready(function() {
var startY= jQuery('#home').position().top + jQuery('#home').outerHeight();
jQuery('#nav-container').html( jQuery('#nav').html());
jQuery(window).scroll(function () {
    if(jQuery(this).scrollTop() > startY ){
        jQuery('#nav-container').slideDown();
    }else{
        $('#nav-container').css({display: 'block'});
        jQuery('#nav-container').slideUp();
    }
});
});
</script>

CSS:

#nav-container {
    position: fixed;
    height: 50px;
    width: 100%;
    min-width: 600px;
    display: none;
}

Any help would be greatly appreciated, thanks guys.

Also, this is my first time messing around with JQuery and JS so be kind.

Final version after fix:

<script type="text/javascript">
$(document).ready(function() {
var startY= $('#home').position().top + $('#home').outerHeight();
var navc = $('#nav-container')
navc.html( $('#nav').html());
$(window).scroll(function () {
    if($(this).scrollTop() > startY ){
        navc.slideDown();
    }else{
        navc.slideUp();
    }
});
});
</script>

Upvotes: 0

Views: 2082

Answers (2)

Andy
Andy

Reputation: 4778

Because you are inside the .scroll() function which gets fired everytime the page is scrolled, it will be going to your else condition and displaying the navbar each time because of this line:

$('#nav-container').css({display: 'block'});

Remove this line and it should work as expected.

Upvotes: 1

Emilio Rodriguez
Emilio Rodriguez

Reputation: 5749

You would need to check if the navBar is show or not and depending on that run the scroll() function only if the state is the correct one. Something like this:

    if(jQuery(this).scrollTop() > startY && $("#nav-container").css('display') == "none" ){
        jQuery('#nav-container').slideDown();
    }else if( && $("#nav-container").css('display') == "block"){
        $('#nav-container').css({display: 'block'});
        jQuery('#nav-container').slideUp();
    }

Upvotes: 0

Related Questions