flex-box horizontal scroll centering on-click

In this example below you will see how to do a flex-box horizontal scroll centering on-click with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by amody, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright amody ©
  • HTML
  • CSS
  • JavaScript
    <div class="container">
    <ul>
        <li class="active"> <a href="#">dude</a>

        </li>
        <li> <a href="#">active</a>

        </li>
        <li> <a href="#">archived</a>

        </li>
        <li> <a href="#">favorite</a>

        </li>
        <li> <a href="#">explore</a>

        </li>
        <li> <a href="#">other</a>

        </li>
    </ul>
</div>

/*Downloaded from https://www.codeseek.co/amody/flex-box-horizontal-scroll-centering-on-click-yJLoqV */
    div.container {
    
    font-family: 'Helvetica Neue', sans-serif;
    font-size: 12px;
    letter-spacing: 1px;
    width: 600px;
    
    overflow: hidden;
    border: 1px solid #3f3f3f;

}

ul {
    display: flex;
    transition: all ease 750ms;
    position:relative;
}

ul li {

    list-style-type: none;
/*     background: green; */

}

ul li a {

    padding: 20px 30px;

  
/*     border-bottom: 4px solid #fff; */
  
    display: block;

    color: #4d4d4d;

    font-weight: bold;

    text-decoration: none;

}

ul li.active {
/*     border-bottom: 4px solid #3f3f3f; */
    background: #efefef;
      border-radius: 35px;


}


/*Downloaded from https://www.codeseek.co/amody/flex-box-horizontal-scroll-centering-on-click-yJLoqV */
    //thank you!
//http://stackoverflow.com/questions/29658893/horizontal-scrolling-list-center-when-needed


var scrollTo = 0;
    $('body').on('click', "a", function () {
        var activeItem = $('li.active');
        var selectedItem = $(this).parent()

        var activeIndex = $('li').index(activeItem);
        var selectedIndex = $('li').index(selectedItem);
        
        scrollTo =- selectedItem.position().left + $('.container').width() / 2 - selectedItem.width() / 2;

        $('ul').css('transform', 'translateX(' + scrollTo + 'px)');
        activeItem.removeClass('active');
        selectedItem.addClass('active');

    });


Comments