I was trying to position horizontal scroll bar at the center of that div. I tired with window.scrollTo() but this works for page scroll and not for div scroll.
$(document).ready(function(){
var outerContentWidth = $('.abc').width();
var scrollPosition = outerContentWidth/2;
$('.abc').scrollLeft(scrollPosition);
});
DEMO: fiddle
This is an old question, but you can now use scrollIntoView
for this, depending on the browsers that must be supported:
$(document).ready(function(){
document.getElementById('center').scrollIntoView({ inline: 'center' });
});
Updated fiddle
The following will give you your desired effect and scroll to the center of the div through a simple change in your jQuery:
$(document).ready(function(){
var outerContent = $('.abc');
var innerContent = $('.abc > div');
outerContent.scrollLeft((innerContent.width() - outerContent.width()) / 2);
});
This code will set the scroll bar to the center of the inner content. But lets examine why. We know the minimum value for scrollLeft is zero, and the maximum is inner.width() - outer.width(). So, half way is easily half the maximum.
There is plenty more information on the subject here.
Demo
$(document).ready(function(){
var scrollPosition = ($('#viewContainer').width()/2 + $('.abc').width())/2;
$('.abc').scrollLeft(scrollPosition);
});
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