Joe Consterdine Joe Consterdine - 1 month ago 9
jQuery Question

Fixed Header Scrolling Issue

I'm creating a fixed nav so when the user scrolls and hits the top of the nav the nav is position:fixed to the top of the screen.

It's more a query than anything else because when the variable 'navOffset' is inside the scroll function the header jitters, but when outside the function it works smoothly.

The class 'fixed' which gets added kept getting added and removed when inside.

Is this because it doesn't have anything time to calculate the offset or something? I couldn't work out why.

Cheers

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style media="screen">
html, body {
padding: 0;
margin: 0;
color: #fff;
}
* {
box-sizing: border-box;
}
.pd {
padding: 8rem;
}
.header {
background: orangered;
}
.section-a {
background: steelblue;
}
.section-b {
background: orange;
}
.section-c {
background: purple
}
.section-d {
background: black;
}
footer {
background: red;
}

nav {
background: #333;
color: #fff;
padding: 3rem 0;
text-align: center;
}

nav ul {
display: inline-block;
}

nav li {
display: inline-block;
padding-right: 5px;
}

.fixed {
top: 0;
left: 0;
width: 100%;
position: fixed;
z-index: 10000;
}
</style>
</head>
<body>
<div class="header pd">
<h1>Header</h1>
</div>
<nav>
<ul>
<li>Section A</li>
<li>Section B</li>
<li>Section C</li>
<li>Section D</li>
</ul>
</nav>
<div class="section-a pd">
<h3>Section A</h3>
</div>
<div class="section-b pd">
<h3>Section B</h3>
</div>
<div class="section-c pd">
<h3>Section C</h3>
</div>
<div class="section-d pd">
<h3>Section D</h3>
</div>
</body>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script type="text/javascript">
(function(){

$(document).on("scroll", function(){
var navOffset = $("nav").offset();
var scrollTop = $(document).scrollTop();

if(scrollTop > navOffset.top) {
console.log(scrollTop);
$("nav").addClass("fixed");
} else {
$("nav").removeClass("fixed");
}
});
}());
</script>
</html>

Answer

Try this. I changed var navOffset = $("nav").position();

(function(){

        $(document).on("scroll", function(){
            var navOffset = $("nav").position();
            var scrollTop = $(document).scrollTop();
console.log(navOffset)
            if(scrollTop > navOffset.top) {
                console.log(scrollTop);
                $("nav").addClass("fixed");
            } else {
                $("nav").removeClass("fixed");
            }
        });
    }());

Comments