I recently encountered an issue while trying to create a sticky navbar that would remain fixed after scrolling past a certain point. I found and customized some code from w3schools that included an animation effect, and it worked perfectly in their demo. However, when I implemented the same code into my own project, it failed to function properly. What could be the reason behind this discrepancy, and how can I rectify it?
For reference, I have shared the relevant code snippet in this fiddle: https://jsfiddle.net/yL3e9Lk4/
I have also created a fiddle for the working demo on W3schools, which you can access here: https://jsfiddle.net/o65zca6w/
Below is the HTML snippet:
// JavaScript code
var navbar = document.getElementById("navbar");
var sticky = stickpoint.offsetTop;
function StickyNav() {
if (window.pageYOffset >= sticky) {
navbar.classList.add("sticky")
navbar.classList.add("slide-in-top")
navbar.classList.remove("nav")
} else {
navbar.classList.add("nav")
navbar.classList.remove("sticky");
navbar.classList.remove("slide-in-top")
}
}
// CSS code
body {
overflow-x: hidden;
margin: 0px;
background: #333;
}
.nav {
list-style-type: none;
overflow: hidden;
display: inline-block;
z-index: 2;
position: absolute;
border: solid;
border-color: red;
}
/* Remaining CSS code omitted for brevity */
<!-- HTML code -->
</div></div>