An interactive jump menu allows users to navigate to different sections on the page by clicking on menu items. However, there seems to be an issue where the page scrolls to the top of the <h3>
element instead of the entire element including any padding applied.
Question:
- Is there a way to scroll directly to the top of an element with padding included?
Current Problem:
https://i.sstatic.net/NeNbf.png
Desired Outcome:
https://i.sstatic.net/U1zg5.png
Code
- You can also view the code on codepen.io.
// JavaScript function to handle scrolling and menu interaction
$(function() {
$(window).on('scroll', function() {
$('.menu').addClass('menu--fixed');
});
$('.menu li a').on('click', function(evt) {
var menuHeight = $('.menu').outerHeight(true);
var elementOffset = ($(this).offset().top) - (menuHeight);
$('html, body').stop().animate({
scrollTop: elementOffset
}, 2000);
evt.preventDefault();
});
});
.container {
max-width: 480px;
}
.heading {
padding: 32px;
background-color: #eee;
}
ul {
list-style: none;
}
.menu {
position: relative;
background-color: black;
color: white;
width: 100%;
display: flex;
justify-between: space-between;
}
.menu li {
display: block;
height: 100%;
}
.menu a {
color: white;
padding: 32px;
}
.menu--fixed {
position: fixed;
top: 0;
left: 0;
margin-top: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="menu__wrapper">
<ul class="menu">
<li><a href="#el1">element 1</a></li>
<li><a href="#el2">element 2</a></li>
<li><a href="#el3">element 3</a></li>
</ul>
</div>
...