I'm looking to create a customized sticky navigation bar through Javascript, but I have never written my own code in this language before.
My approach involves implementing two sticky navigation bars that appear and disappear based on scrolling behavior. Here's how I envision it:
- Initially, the first navigation bar (yellow) will be visible with a position 100px from the top, set as
top:100px
. - Upon scrolling, I want the yellow
<div>
to vanish usingdisplay:none
. - Simultaneously, as the yellow navigation bar disappears, I intend for the orange navigation bar to appear with
top:200px
. - Currently, the orange bar is displayed at the start when it shouldn't... only one bar should be shown at any given moment. I expect the bars, both
<div>
elements, to continue appearing and disappearing even with multiple scrolls up and down.
There seems to be an issue with my javascript code and Codepen is indicating that $
is undefined.
https://codepen.io/G1111/pen/RwBPrPR
$(window).scroll(function() {
Testvariable = $(window).scrollTop();
if (Testvariable == 0) {
document.getElementById("stickys").style.display = "normal";
document.getElementById("stickys2").style.display = "none";
} else {
document.getElementById("stickys").style.display = "none";
document.getElementById("stickys2").style.display = "normal";
}
});
#stickys {
top: 100px!important;
background-color: yellow;
height: 100px;
position: fixed;
position: fixed!important;
box-sizing: border-box;
margin: 0 0% 0 0%!important;
padding: 0!important;
width: calc(60vw - 0%);
left: calc(20vw - 0%);
right: calc(20vw - 0%);
width: calc(100vw - 0%);
left: 0px;
right: 0px;
opacity: 1;
}
#stickys2 {
top: 200px!important;
background-color: orange;
height: 100px;
position: fixed;
position: fixed!important;
box-sizing: border-box;
margin: 0 0% 0 0%!important;
padding: 0!important;
width: calc(60vw - 0%);
left: calc(20vw - 0%);
right: calc(20vw - 0%);
width: calc(100vw - 0%);
left: 0px;
right: 0px;
opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="stickys">
My first sticky navigation bar. Show initially, then hide when slighest scroll, that is when Testvariable>0. Here, top:100px
</div>
<div id="stickys2">
My second sticky navigation bar. Hide initially, then show when slighest scroll, that is when Testvariable>0. Here, top: 200px.
</div>
.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>