I'm encountering an issue with smooth scrolling on a webpage that has a sticky header. When I click on a navigation link to scroll to a specific section using
scrollTop: href.offset().top - 100
, the page doesn't behave as expected. It seems to bounce back to the top after initially scrolling to the desired section. I am working in Microsoft Edge, and I suspect this may be contributing to the problem.
HTML
<!DOCTYPE HTML>
<html lang="en">
<head></head>
<body id="home">
<nav><a href="#section1">Section #1</a></nav>
<main>
<!-- INSERT A BUNCH OF <BR> TAGS -->
<h2 id="section1">section1</h2>
<!-- INSERT A BUNCH OF <BR> TAGS -->
</main>
</body>
</html>
CSS
nav {
position:fixed;
padding:4px;
border:2px solid #000;
width:100%;
line-height:2.25em;
background-color:yellow;
}
h2 {
padding:4px;
border:1px solid #000;
width:100%;
line-height:100px;
background-color:red;
}
jQuery
$(document).ready(function() {
$('a[href*="#"]').click(function(event) {
var href = $(this.hash);
if (href.length) {
event.preventDefault();
$('html, body').animate({
scrollTop: href.offset().top - 100
}, 750, function() {
location.hash = href.attr('id');
});
}
});
});
EDIT:
I've learned that using display:fixed
on a <div>
element can cause it to be removed from the normal flow of the page, potentially causing issues like the one described above. I'm wondering if there's a workaround for this particular situation?