Reputation: 33
Heey everyone,
I have build this horizontal scrolling website, but when I click on a link from the nav bar, the div appears on the right of the screen and not in the center. Does anyone know how to fix this?
Here is the jquery code I have used:
$(function() {
$('.fixed-nav-bar li, .fixed-nav-bar a').bind('click',function(event){
var $anchor = $(this);
$('html, body').stop().animate({
scrollLeft: $($anchor.attr('href')).offset().left
}, 1500,'easeInOutExpo');
$('html, body').stop().animate({
scrollLeft: $($anchor.attr('href')).offset().left
}, 1000);
event.preventDefault();
});
Thanks in advance!
Upvotes: 0
Views: 68
Reputation: 13489
scrollLeft
should be $($anchor.attr('href')).offset().left + ($(window).width() - $($anchor.attr('href')).width()) * 0.5
The part after the plus calculates the window width, subtracts the element width, and adds half of the difference to scrollLeft, resulting in the target being in the center.
You should probably clean up my example code a bit to make it more readable, but the concept should be clear.
Upvotes: 1