jQuery - Scroll element to the middle of the screen instead of to the top with an anchor link
Here's how to do it with plain JQuery using scrollTo()
$('.main-nav a').on('click', function(e) {
var el = $( e.target.getAttribute('href') );
var elOffset = el.offset().top;
var elHeight = el.height();
var windowHeight = $(window).height();
var offset;
if (elHeight < windowHeight) {
offset = elOffset - ((windowHeight / 2) - (elHeight / 2));
}
else {
offset = elOffset;
}
var speed = 700;
$('html, body').animate({scrollTop:offset}, speed);
});
This is a combination of straker's code and code from this question: jQuery scrollTo - Center Div in Window Vertically
The API provides a way to execute a smoothScroll not bound to an element.
You'll want to execute this method inside an onclick event for the anchor tags so that you can have access to it's target. Then you can calculate what you need to to get to the desired position. Since offset
is now an absolute offset instead of a relative offset, you'll need to get the exact position to scroll to.
$('.main-nav a').on('click', function(e) {
var el = $( e.target.getAttribute('href') );
var elOffset = el.offset().top;
var elHeight = el.height();
var windowHeight = $(window).height();
var offset;
if (elHeight < windowHeight) {
offset = elOffset - ((windowHeight / 2) - (elHeight / 2));
}
else {
offset = elOffset;
}
$.smoothScroll({ speed: 700 }, offset);
return false;
});
Here a sure shot way to do it
var $window = $(window),
$element = $('.my-element'),
elementTop = $element.offset().top,
elementHeight = $element.height(),
viewportHeight = $window.height(),
scrollIt = elementTop - ((viewportHeight - elementHeight) / 2);
$window.scrollTop(scrollIt);