Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript jquery find left position of element in horizontal scroll container

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' });
like image 539
sadmicrowave Avatar asked Jun 19 '11 01:06

sadmicrowave


2 Answers

You can use the scroll position in the container element like this;

$('#container .element').offset().left - $('#container').offset().left + $('#container').scrollLeft();

See JSFiddle here

like image 71
Danielle Avatar answered Sep 28 '22 07:09

Danielle


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');
like image 34
user2908825 Avatar answered Sep 28 '22 08:09

user2908825