Jump to content

fix nav to top on scroll


rich_web_development

Recommended Posts

Hi,

 

I was wondering if anyone could help me.

 

I have managed to get the navigation bar under my header to collapse into a menu when the screen size gets smaller than 680px.

I watched a YouTube video on how to get the navigation bar to stick to the top of the screen on scroll.

 

The problem is when the screen is smaller than 680px the navigation bar sticks to the top UNTILL the menu toggles to show the navigation options then the navigation no longer sticks to the top.

 

The jQuery looks like this:

 

jQuery(document).ready(function(){

var navOffset = jQuery(".topnav").offset().top;

jQuery(".topnav").wrap('<div class="nav-placeholder"></div>');

jQuery(".nav-placeholder").height(jQuery(".topnav").outerHeight());

 

jQuery(window).scroll(function(){

var scrollPos = jQuery(window).scrollTop();

 

if(scrollPos>=navOffset){

jQuery(".topnav").addClass("navfixed");

 

}else{

jQuery(".topnav").removeClass("navfixed");

}

 

 

});

 

});

 

I've included the css and html I'm using. If someone could please tell me how to get the navigation bar to stick to the top even when the menu is clicked.

Thanks

 

 

testFIX.css

testFIX.html

Link to comment
Share on other sites

What happens when you click? Does it add a new class that overrides the other behavior?

Thanks for the reply.

 

The jQuery adds the new class 'fixednav' when on scroll which works fine until the screen goes below 680px. I have the css set so that the navigation bar changes to just display 'menu' and then toggles when clicked to display the navigation options(I used the code that's on the RWD bit of w3schools css). When the screen is below 680px the navigation bar shows only the menu and when you click menu it shows the navigation options.

 

When you click on the menu the navigation bar no longer stick to the top. If you open the f12 tools you can see the .fixednav gets overwritten by the css 'ul.topnav.responsive' which gives it a position of relative.

 

I want the navigation bar to stay stuck to the top even when the menu is clicked.

Link to comment
Share on other sites

You'll need to find what is changing the CSS styles and either remove that so that doesn't make the change, or change the CSS to not override the display property.

 

Ok. How stupid of me. That was simple. Think I've fixed it now.

Changed the CSS to:

@media screen and (max-width: 680px){ul.topnav.responsive{position: fixed;right:0px;width:100%;top:0px;}

 

Thank you very much for your help!

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...