1

I am trying to make a div visibe only after a certain scroll length. There are already some threads here on Stackoverflow about it and so I have tried to use the suggested scripts listed in the answers, but no one of them seems to work.

So, I suppose that I don't know how to use them.

I have put this block into the head, surrounded by the two script tags:

function scroll_bar() {
    if (document.body.scrollTop > 700) {
        document.getElementById("navigation_bar").show();
    }
    else
    {
        document.getElementById("navigation_bar").hide();
    }
}

And in the body, I have a div (the one that I want to make visible/hidden) with these attributes:

<div onload="scroll_bar();" class="container" id="navigation_bar" style="position: fixed; z-index: 1; background-color: white; height: 50px; width: 100%;"></div>

What is wrong over here? (I am using Bootstrap anyway, that "container" class comes from it.)

Adeel
  • 2,901
  • 7
  • 24
  • 34
Antonio
  • 11
  • 2

4 Answers4

2

You have to add an event listener to the 'scroll' event: window.addEventListener('scroll', scroll_bar). Also in your handler I would use window.pageYOffset instead of document.body.scrollTop.

0

Instead of putting your <script> in your <head>, put in just before your closing body tag (</body>). This will make sure that content is loaded before the script and therefore your script should run correctly.

  <p>I'm some content!</p>

  <script>console.log('JavaScript!');</script>

</body>

Also, you need to make sure that your script function fires on the body scroll event.

sdr981
  • 405
  • 4
  • 15
0

Are U sure it's good??

document.getElementById("navigation_bar").show();

"document.getElementById("navigation_bar")." is javascript.

"show()" is jquery.

try:

document.getElementById("navigation_bar").style.display = 'block'/'none'

or

$("#navigation_bar").show();
LuckyLue
  • 158
  • 9
  • Oh many thanks I didn't knew that. Jquery is included anyway because I'm using Bootstrap and it is there by default... – Antonio Oct 12 '17 at 11:59
0

You misplaced your event to div.

please move your event BODY

code

<body onload="scroll_bar();" >
<div class="container" id="navigation_bar" style="position: fixed; z-index: 1; background-color: white; height: 50px; width: 100%;"></div>
</body>
HD..
  • 1,456
  • 3
  • 28
  • 48