Jquery: scrollLeft animation

I am new to jquery and cannot understand why my code is not working. I have a horizontal layout and want to use the scrollLeft () function (which works fine with this code)

$("#next").click(function() { currentElement = currentElement.next(); scrollTo(currentElement); }); function scrollTo(element) { $(window).scrollLeft(element.position().left); } 

But ideally, I would like to animate this, so when you press #next there is a nice animated effect for the left scroll function

 $("#next").click(function() { currentElement = currentElement.next(); scrollTo(currentElement); }); function scrollTo(element) { $(window).animate({scrollLeft: element.position().left}, 750); } 

But to no avail. What am I doing wrong?

+43
jquery jquery-selectors
Jul 29 2018-11-28T00:
source share
2 answers

You need something like this:

 $("#next").click(function(){ var currentElement = currentElement.next(); $('html, body').animate({scrollLeft: $(currentElement).offset().left}, 800); return false; }); 
I believe this should work, it adopted from a scrollTop function.
+61
Jul 29 '11 at 15:02
source share

First of all, I should note that css animation will probably work best if you do it a lot, but I ended up getting the desired effect by wrapping .scrollLeft inside .animate

 $('.swipeRight').click(function() { $('.swipeBox').animate( { scrollLeft: '+=460' }, 1000); }); $('.swipeLeft').click(function() { $('.swipeBox').animate( { scrollLeft: '-=460' }, 1000); }); 

The second parameter is speed, and you can also add the third parameter if you use some kind of smooth scroll.

+25
Oct 10 '14 at 1:21
source share