Вопрос

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>
Это было полезно?

Решение

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.

Другие советы

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();
    }
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top