Reputation: 1
The page has a sticky navbar
that stay on screen all the time.
When I am scrolling to the next section(div
) of the page, it will scroll so the div starts at the top of the screen , so the navigation bar cover it a little bit.
How to minus from y scrolling position the navigation bar height ?
$('html, body').animate({
scrollTop: $("#section2").offset().top // minus the nav height
}, 1000);
Also - how to make this navbar
height
available to my javascript (from the css) using a good practice ? (global var?)
Upvotes: 0
Views: 3820
Reputation: 170
To know the height of any element :
Go to the Inspector (Ctrl+Shift+i), select the 'nav' element and on the right side, click the box-model. This will give you the height and width of the selected element.
In JavaScript, to get the height :
$("nav").height();
Upvotes: -1
Reputation: 50674
You can select your navigation bar (here I gave my navigation bar the id nav
) and get its height by doing:
$("#nav").height();
You can then subtract this from the scrollTop property.
However, do note, if your nav bar has padding and/or a margin, to correctly calculate the height you will need to use a different method from .height
. See this answer if you're having difficulties.
See working example below:
$('html, body').animate({
scrollTop: $("#section2").offset().top - $("#nav").height() // minus the nav height
}, 1000);
body {
margin: 0;
}
nav {
background: black;
height: 10vh;
width: 100%;
position: fixed;
}
section {
height: 100vh;
}
#section1 {
background: red;
}
#section2 {
background: lime;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav id="nav"></nav>
<section id="section1">Top</section>
<section id="section2">Top</section>
Upvotes: 4