Jquery jquery find the left position of an element in a horizontal scroll container

I have an overflow container: auto that spans a document window width of 400% wide. Therefore, my page has a horizontal scrollbar. I also have several divs inside this container with different left positions. I need to get the left position of each container when I click on them. I am using $ (this) .offset (). Left, but that gives me the offset to the left of the div container, which is 0px, and I used $ (this) .position (). Left, but that gives me the same ... any suggestions?

The markup is as follows:

<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' }); 
+4
source share
5 answers

Since, for some reason, I still cannot get .offset () to work as it should, or scrollLeft (). I just decided to make it very cool.

  $('.container').click(function(){ var num = parseInt( $(this).attr('rel') ); var left = $('.container').width() * num-1; var top = $('.container').css('top'); //do something with these values }); 
0
source

You can use the scroll position in the container element as follows:

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

See JSFiddle here

+2
source

You tried something like this ...

 $('#id').width(); 
0
source

I have not used it before, but I think it works similar to scrollTop - see scrollLeft () One thing you will need to find is the starting position of the scroll element of the Left before scrolling and caching it, and then subtracting it from the new scrollLeft position obtained after scrolling .

change Waiting, offset () not working? It should work.

0
source

Use position() instead of offset if you have problems with offset. Use the width () of the object you are scrolling to account for it. Of course, you can change the types of selectors to use identifiers or something suitable for 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'); 
0
source

All Articles