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?
To animate scrollLeft using jQuery, use the animate() method with scrollLeft.
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.
scrollLeft property gets or sets the number of pixels that an element's content is scrolled from its left edge.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With