I am using jquery to scroll to sections of my page.
Here’s the code:
// Scroll to element
$('#menu li a').click(function(){
var elementId = $(this).attr('href');
$('html, body').animate({ scrollTop: $(elementId).offset().top }, 1600);
return false;
});
<ul id="menu">
<li><a href="#item1">1</a></li>
<li><a href="#item2">2</a></li>
</ul>
<div id="item-1">placeholder-1</div>
<div id="item-2">placeholder-2</div>
As you can see I’m grabbing the href (#id) of an target element from the menu link and scrolling to the target element.
But the issue lies in the fact that I have target elements going right to the bottom of the page, and when the page is scrolled to the last, the top of that element can’t scroll to the top of the page as there is not enough page left at bottom… Am I making sense?
I’m trying to work out a solution using css or jquery that would mean that regardless of the height of the page (or padding/margin at bottom) the element will be at the top of the viewport when a menu item is clicked.
Do I add more padding based on the height of the viewport using javascript? Do I use some kind of overflow trick?
Your problem is that the page isn’t as tall as you want it to be. If you try to go to
#xand#xis at the bottom of<body>, then you’ll scroll to the bottom of the page and#xwill be at the bottom of the window when you want it at the top.I think your only choice is to force the
<body>to be taller. Something like this:Something like that will append a (visually) empty
<div>to the bottom of your content, this extra<div>will have the same height as the browser’s viewport and this extra height will let you always scroll your elements right to the top of the viewport.