Nguyễn Huy
Nguyễn Huy

Reputation: 227

Problems with menu fixed top on scroll, when html document not enough height?

I do a menu fixed top when scroll, it ok with some pages have large height, but in page has not enough height, this script loop:

Example:

I have menu with height 50px and i write a script:

if ($(this).scrollTop() > 50){
    // add class fixed
} else { //remove class }

Please see this example: http://jsfiddle.net/F4BmP/2930/

Upvotes: 3

Views: 3203

Answers (4)

Nguyễn Huy
Nguyễn Huy

Reputation: 227

Finally, i find a solution for my problem.

Reason make problem is HTML document lost height when menu change from static to fixed.Examble: Browser has 500px and has a scrollbar, when user scroll my menu change to fixed and browser lost 50px of menu, so browser not enough height to has scrollbar, it will return to top page and do code lines in ELSE statement.

So i add a div wrap my menu and set height the same height with my menu, this will make the height of document always the same on before and after scroll:

<div id="wrap" style="height:50px;width:100%">
      <div id="mymenu"></div>
</div>

This solution solve my problem.

Upvotes: 2

Alexander Solonik
Alexander Solonik

Reputation: 10230

I tested your code in firefox and also in chrome , the issue seems to be in chrome . i reworked the code both html and JS and it works fine in chrome, for for that matter in any browser .

heres what should probably work for you :

 $(document).ready(function(){
             $(window).scroll(function (e) {
                    $el = $('.nav');
                    if ($(this).scrollTop() > 100) {
                        $('.nav').addClass("fixedNav");
                    }else {
                        $('.nav').removeClass("fixedNav");
                    }
                });
             });

the entire code is enclosed in a fiddle .

Link to fiddle

Kind regards .

Alexander .

Upvotes: 0

shanidkv
shanidkv

Reputation: 1103

Basic concept is user has to see the menu while scrolling the page.

But in your functionality is correct.There is no much content and User can see the menu in current screen itself. If there is more content user can scroll and get sticky menu always on top.

If you really want to make browser scroll you can give min-heightfor container.

Example

.containerclassname{
  min-height: 1500px;
}

Upvotes: 0

Ujang Hardman
Ujang Hardman

Reputation: 115

Use this javascript:

$(document).ready(function(){
var elementPosition = $('.menu').offset();

$(window).scroll(function(){
        if($(window).scrollTop() > elementPosition.top){
              $('.menu').css('position','fixed').css('top','0');
              $('.menu').css('width','100%');
              $('.menu').css('z-index','500');
        } else {
            $('.menu').css('position','static');
        }    
});
});

Well, this code is working on my menubar, even if screen size is different .

Upvotes: 0

Related Questions