Nociph Nociph - 4 months ago 12
Javascript Question

Show or hide HTLM according to the position of the user in the page

I want to create a horizontal navbar on my website.
I also want it to aprear and disapear "dynamically",
according to the position of the user in the page, but i can't manage to
do it properly. Here's my code :

HTML:

<script src='scripts/navbar.js'></script>
<ul id="navbar" onscroll="showHideNavbar();">
<li>LOGOHERE</li>
<li><a id="home-link-navbar">Home</a></li>
<li><a id="projects-link-navbar">Projects</a></li>
<li><a id="about-link-navbar">About</a></li>
<li><a id="contact-link-navbar">Contact</a></li>
</ul>
<script type="text/javascript">
showHideNavbar();
</script>


and JS in navbar.js:

function showHideNavbar()
{
console.log(window.pageXOffset);
if(window.pageXOffset < 1000){
document.getElementById("navbar").style.opacity = 0;
}
if(window.pageXOffset > 1000 && window.pageXOffset < 2000){
document.getElementById("navbar").style.opacity = window.pageXOffset/10000*5;
}
else{
document.getElementById("navbar").style.opacity = 1;
}
}


Can you help me ?

Answer

You need to call this function periodically, but you do it just once.

Do that with setInterval()

<script type="text/javascript">
    setInterval(showHideNavbar,100);
</script>

Also, pageXOffset is the horizontal offset, but you seem to want pageYOffset.