Ceylan Mumun Kocabaş
Ceylan Mumun Kocabaş

Reputation: 527

Set percentage value to scrollLeft() in jQuery

This is a little bit confusing (and I thought that it's impossible). I found how to get the percentage of scroll amount from Blazemonger's answer on SO:

scrollPercentage = 100 * $(this).scrollLeft() / ($('#contained').width() - $(this).width());

Ok, this solution works great, but my question is how can I set the scroll amount with jQuery?

I am simultaneously scrolling two scrollable divs and I tried this:

$(".mycontainer").scroll(function(){    
    var scrollPercentage = 100 * $(this).scrollLeft() / ($(".mycontainerContent").width() - $(this).width())
        $(".anotherContainer").scrollLeft(scrollPercentage);
});

But that code doesn't work.

I tried by adding the percent symbol but the result is the same - nothing happens.

$(".mycontainer").scroll(function(){    
    var scrollPercentage = 100 * $(this).scrollLeft() / ($(".mycontainerContent").width() - $(this).width())
        $(".anotherContainer").scrollLeft(scrollPercentage.toFixed(0)+'%');
});

Any ideas?

EDIT - jgasiorowski's answer is kind of working:

You need to change percentage value again to original type for scroll

 var scrollValueForAnother = ($(".anotherContainer").width() -
 $(this).width()) * (percentage / 100);
 $(".anotherContainer").scrollLeft(scrollValueForAnother);

I hope that I didn't make a mistake in calculations

but like I mentioned in the comment of his answer:

it's kind of working, but $(".anotherContainer") reaches end before $(".myContainer") reaches its end. I want to sync two scrollable areas to reach their end of scroll at the same time. i hope that i could explain it.

*the two scrollable areas got different widths!

Upvotes: 1

Views: 5703

Answers (1)

jgasiorowski
jgasiorowski

Reputation: 1033

You need to change percentage value again to original type for scroll

var scrollValueForAnother = ($(".anotherContainer").width() - $(this).width()) * (percentage / 100);
$(".anotherContainer").scrollLeft(scrollValueForAnother);

I hope that I didn't make a mistake in calculations

EDIT2: I made that little fiddle https://jsfiddle.net/b4d9bLnm/1/ so your code should look like that:

$(".mycontainer").scroll(function(){  
    var container2 = $(".anotherContainer");  
    var scrollPercentage = 100 * $(this).scrollLeft() / (this.scrollWidth - this.clientWidth);

    var scrollValueForAnother = (container2[0].scrollWidth -  container2[0].clientWidth) * (percentage / 100);
    $(".anotherContainer").scrollLeft(scrollValueForAnother);
});

Upvotes: 1

Related Questions