Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery: animate scrollLeft

I'm quite new to jquery and can't seem to figure out why my code isn't working. I have a horizontal layout and want to use the scrollLeft() function (which works perfect 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 that when #next is clicked there is a nice animated effect to the scroll left 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?

like image 874
bswinnerton Avatar asked Jul 29 '11 14:07

bswinnerton


People also ask

How do you animate in scrollLeft?

To animate scrollLeft using jQuery, use the animate() method with scrollLeft.

How do I scroll left and right in jQuery?

The scrollLeft() method sets or returns the horizontal scrollbar position for the selected elements. Tip: When the scrollbar is on the far left side, the position is 0. When used to return the position: This method returns the horizontal position of the scrollbar for the FIRST matched element.

What is scrollLeft?

scrollLeft property gets or sets the number of pixels that an element's content is scrolled from its left edge.

How do I horizontally scroll a div using jQuery?

In jQuery, we can make any element tag move horizontally using the built-in function scrollLeft() function for scrolling the scrollbar horizontally according to either the position which is set as the parameter or without setting the position which would specify the position in pixel number of the scrollbar.


2 Answers

You'll want 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's adopted from a scrollTop function.
like image 181
ayyp Avatar answered Oct 09 '22 10:10

ayyp


First off I should point out that css animations would probably work best if you are doing this a lot but I ended 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 a third parameter if you are using smooth scrolling of some sort.

like image 23
Colin Avatar answered Oct 09 '22 11:10

Colin