jquery: animate scrollLeft

JqueryJquery Selectors

Jquery Problem Overview


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?

Jquery Solutions


Solution 1 - Jquery

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.

Solution 2 - Jquery

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbswinnertonView Question on Stackoverflow
Solution 1 - JqueryayypView Answer on Stackoverflow
Solution 2 - JqueryColinView Answer on Stackoverflow