jQuery Smooth Horizontal Scroll

SlightlyClever picture SlightlyClever · Oct 14, 2013 · Viewed 8.4k times · Source

I've created a long horizontal page and using anchors to navigate to section's within the page. I added a jQuery smooth scrolling function but it's not taking affect?

Here's the navigation:

<ul class="nav">
<li><a href="#starters">Starters</a></li>
<li><a href="#main">Main Dishes</a></li>
<li><a href="#special">Special Dishes</a></li>
<li><a href="#side">Side Dishes</a></li>
</ul>

Within the content i've added corresponding anchors:

<a name="starters"></a>

And here's the jQuery function:

$(function() {
$('ul.nav a').bind('click',function(event){
    var $anchor = $(this);

    $('html, body').stop().animate({
        scrollLeft: $($anchor.attr('href')).offset().left
    }, 1500, "easeInOutExpo");
    event.preventDefault();
});
});

The anchor's work fine, clicking the navigation takes you to the desired section but it jumps instead of scrolling.

Any ideas why??

Answer

Maulik picture Maulik · Mar 31, 2017

It's simple add class to your div which need to scroll for example below:

<ul class="nav">
<li class="a"><a href="#starters">Starters</a></li>
<li class="b"><a href="#main">Main Dishes</a></li>
<li class="c"><a href="#special">Special Dishes</a></li>
<li class="d"><a href="#side">Side Dishes</a></li>
</ul>

Now, your js will be like this:

$(function() {
$('#clickable element').bind('click',function(event){
    $('#targetelement or div').stop().animate({
        scrollLeft: $('.a').offset().left
    }, 500);
    event.preventDefault();
});
});

likewise you can build js for b,c,d classes.