0

Have put together a sticky navbar (jsfiddle) that comes into view only after the user scrolls down 10px from the top of the document. However as seen in the fiddle; using:

$(window).scroll(function () {
    if ($(this).scrollTop() > 10) {
     document.getElementById('navig').style.visibility = 'visible';

this only works in the first instance after the code is run. In subsequent similar actions (after scrolling down the document completely and scrolling back up again) in the same session, the navbar comes into appearance much further down than 10px. It only works again on refresh (rereun) and that too again, only the first instance of top to bottom scrolling.

Also, I'd want the effect to act on scrolling back up ie. the fixed navbar should become absolute at the base of the header when the user moves past that point. And it should hide when scrolling past 10px from top. There isn't a scrollBottom() function, so how is this handled?

This fiddle has jquery loaded: https://jsfiddle.net/6ss64s7e/

How can these issues be addressed? (pardon, am new to javascript).

Community
  • 1
  • 1
Agni Scribe
  • 252
  • 3
  • 18

1 Answers1

1

Before you return to the value position:absolute; you have to delete all the other properties that you added because they won't be automatically deleted - so, you don't need top:0; anymore.

You can delete the top:0; property by passing empty string to its value, like this:

$('#navig').css({'position':'absolute','top':''});

For the detection of scroll and its direction, see this question.

Community
  • 1
  • 1
Nomce
  • 738
  • 1
  • 6
  • 18
  • thanks! I don't entirely understand why top:' ' works, but am going over it slowly. thanks again. – Agni Scribe Jan 30 '16 at 15:30
  • 1
    You are welcome! `top:' '` works because when you change to position:fixed; you also add `top: 0;`, and to return it to the previous state you have to change to `position:absolute` but also remove the value for the top property, and with jQuery you remove the property by passing empty string. – Nomce Jan 30 '16 at 15:36