I'm trying to replicate this jsfiddle, which sticks the bar to the top when scrolling down; but there is something wrong which I am not able to identify.
To go to the most basic approach possible, I want to avoid links between files and therefore include everything inside the same html file, following this structure:
<html>
<head>
<style>
/* css here */
</style>
</head>
<body>
<!-- html here -->
<script>
// javascript here
</script>
</body>
</html>
Here is how it looks like:
<html>
<head>
<style>
html, body {
min-height: 100%;
padding: 0;
margin: 0;
}
.stick {
position: fixed;
top: 0;
}
#a8 {
height: 50px;
width: 100%;
background: #DDD;
}
</style>
</head>
<body>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div id="a8"></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>
<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>
<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>
<script>
var top = document.getElementById('a8').offsetTop;
window.onscroll = function() {
var y = (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
if (y >= top) {
a8.className = 'stick';
}
else {
a8.className = '';
}
};
</script>
</body>
</html>
After checking for similar questions (here, here and here), all of them refer to the fact that the page is not yet rendered when the js code runs. Placing the js at the bottom (which I have already done) should solve the problem; but anyway I have also tried wrapping js with
$(document).ready(function() {
// code here
});
and
window.onscroll = function() {
// code here
});
and
$(window).onload(function(){
// code here
});
but did not help.
What am I missing?