brunodd brunodd - 5 months ago 12
CSS Question

Center scroll horizontally according to active link

How can I center the scroll horizontally according to active link using jQuery?

I am using

overflow-x: scroll;
in order to enable horizontal scroll but I wanted the scroll to be centred according to the active link.

This is what I am trying to achieve:

enter image description here

Example

$(document).ready(function () {
$('a[href^="#"]').on('click', function (e) {
e.preventDefault();
$(document).off("scroll");

$('a').each(function () {
$(this).removeClass('active');
})
$(this).addClass('active');
});
});

function onScroll(event){
$('#menu-center a').each(function () {
var currLink = $(this);
var refElement = $(currLink.attr("href"));
currLink.removeClass("active");
});
}

Answer

AFAIK you'll need to use JavaScript to scroll automatically when you land on the page. You can do something like...

$(document).ready(function () {
    $('a[href^="#"]').on('click', function (e) {
        e.preventDefault();
        $(document).off("scroll");

        $('a').each(function () {
            $(this).removeClass('active');
        })
        $(this).addClass('active');
        var myScrollPos = $('a.active').offset().left + $('a.active').outerWidth(true)/2 + $('.menu').scrollLeft() - $('.menu').width()/2;
        $('.menu').scrollLeft(myScrollPos);
    });
});

You can adjust myScrollPos to get it to stop where you want it to, this should make it scroll to the left side of your active button. Breakdown below!

$('a.active').offset().left + $('a.active').outerWidth(true)/2

This gets us the button's distance from the visible edge of the element it's contained in, in this case the menu, then subtracts half the button's width to get the returned value to be the center of the button instead of the edge. It doesn't include any scrolling that's been done on the parent, so from here we add

+ $('.menu').scrollLeft()

Into the mix, that way we get the menu item's distance from the left, plus the current scroll position. The combination of the two gets us a consistent scroll coordinate between each button. Then, to wrap it up,

- $('.menu').width()/2

Offsets the scroll by negative 1/2 of your menu's width, effectively centering the button!

*Updated with the final solution!