Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center scroll horizontally according to active link

Tags:

jquery

css

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");
    });
}
like image 896
brunodd Avatar asked Jul 05 '16 15:07

brunodd


2 Answers

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!

like image 61
will Avatar answered Sep 19 '22 06:09

will


$(document).ready(function () {
    var element = document.querySelector(".menu a.active");
    element.scrollIntoView({behavior: "smooth" ,inline: "center"});
});

might do the same.

like image 20
olav_1985 Avatar answered Sep 21 '22 06:09

olav_1985