I have a overflow:auto container that spans 400% width of the document window. Therefore I have a horizontal scrollbar on my page. I also have multiple div's inside this container with different left positions. I need to get the left position of each container as I click on them. I use $(this).offset().left but that gives me the left offset of the container div which is 0px and I've used $(this).position().left but that gives me the same thing.... any suggestions?
Markup looks like this:
<div id='scroll'>
<div id='content'>
<div class='container' rel='1'></div>
<div class='container' rel='2'></div>
<div class='container' rel='3'></div>
<div class='container' rel='4'></div>
</div>
</div>
css
#scroll{
position:absolute;
width:100%;
height:95%;
overflow:auto;
}
#content{
float:left;
height:100%;
}
.container{
height:100%;
float:left;
}
jquery
var iMaxSize = $(".container").size();
$("#content").css({width: $(document).width()*iMaxSize +'px' });
$(".container").css({width: $("#content").width()/iMaxSize +'px' });
You can use the scroll position in the container element like this;
$('#container .element').offset().left - $('#container').offset().left + $('#container').scrollLeft();
See JSFiddle here
Use position()
instead of offset if you having trouble with offset.
Use width() of the object your scrolling to account for it.
Of course you can change the selector types to use ids or whatever fits your situation.
$('.class for container div')
.animate( { scrollLeft:
$('.class for you want to scroll to').position().left -
$('.class for you want to scroll to').width() }
,'slow');
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