stacky
stacky

Reputation: 311

Navigation bar fixed after scroll?

I have a navigation bar after header and i want that to be stuck at top of the page while scrolling down.

can i do with position:relative?? Unlike position:fixed with the help of the following script or any other better way?

$(window).scroll(function () {
if ($(window).scrollTop() > 100) {
    $('#header').css('top', $(window).scrollTop());
}});

here is my fiddle!

black color background bar to be stuck at the top of the page

please help me out to fix that, thank you in advance.

Upvotes: 2

Views: 13143

Answers (2)

mcrum
mcrum

Reputation: 1

you can solve it with css:

html:

    <nav id= "header">
      <ul>
        <li><a href="#"> Link 1 </a></li>
        <li><a href="#"> Link 2 </a></li>
        <li><a href="#"> Link 3 </a></li>
      </lu>
    </nav>

css:

    #header{
    position: sticky;
    top: 0; /* Position where u want it to stick, can be a
               percentage, px, vh or any position unit */
    z-index:150; /* to keep it on top layer in order not to be 
                    masked by another element*/
    }

check this link: https://elextutorial.com/learn-css/css-position-fixed-scroll-sticky/

Upvotes: -1

akinuri
akinuri

Reputation: 12037

Is this what you're trying to get?

window.onscroll = changePos;

function changePos() {
    var header = document.getElementById("header");
    if (window.pageYOffset > 70) {
        header.style.position = "fixed";
        header.style.top = "0";
    } else {
        header.style.position = "";
        header.style.top = "";
    }
}

Update: (I think, not sure) you can't scroll a fixed element, but you can an absolute one. So in the code below we're using position: absolute but making it behave like it's fixed. Now you can see the #header when you zoom in and scroll down.

window.onscroll = changePos;

function changePos() {
    var header = document.getElementById("header");
    if (window.pageYOffset > 70) {
        header.style.position = "absolute";
        header.style.top = pageYOffset + "px";
    } else {
        header.style.position = "";
        header.style.top = "";
    }
}

FIDDLE

Upvotes: 5

Related Questions