How to get the offset of the left float when it is out of the viewport?

Here is my situation. I created several panels stacked side by side, which are wrapped in a main container. Each panel occupies 100% of the width and height of the viewport. My goal is to scroll horizontally across each panel when I click on their respective link. This works great using a clean css approach. However, I am learning jQuery and I want to use the .scrollTo () method to achieve this.

When the panels were stacked one after another (i.e. vertically), I was able to get the top offset of each panel and scroll well to their position.

With horizontal change, I am having problems to get the left panel offset. I get a left zero offset for all of them. If my logic is correct, say that the viewport has a width of 1920 pixels, the second offset of the left panel should be equal to 1920 pixels, the third - 3840 pixels, etc.

From the information that I have collected so far, this is because the panels are outside the viewing area. Indeed, I applied a width of 20% to the panels so that they were all visible in the viewport, and I tried to prevent them from shifting to the left. They were requested to me successfully.

So how do I get around this problem? It may seem like I'm reinventing the wheel, but as I said, I'm learning jQuery, so I need to understand why it behaves as such and how I can solve it. Any help would be greatly appreciated :) Below are snippets of what I have so far.

Thanks.

Markup:

<div class="mainWrapper"> <section class="panel" id="panel-1"></section> <section class="panel" id="panel-2"></section> <section class="panel" id="panel-3"></section> <section class="panel" id="panel-4"></section> </div> 

CSS:

 .mainWrapper, .panel { position: relative; height: 100%; } .mainWrapper { top: 0; left: 0; } .panel { display: inline-block; background: rgba(255, 255, 255, 1); } 

Javascript:

 $(document).ready(function() { var $panelWrapper = $('.mainWrapper'); var $panels = $('.mainWrapper').find('.panel'); var $panelScrollPos = new Array(); $panels.each(function(i) { //This is where I need help. It not working $panelScrollPos[i] = Math.round($(this).offset().left - $panelWrapper.offset().left); alert('Panels position are: ' + $panelScrollPos[i]); }); }); 

Note that I used the .width () method to set the width of .mainWrapper and .panel. I did not include it in the snippet since it works.

+5
source share
2 answers

To be able to set inline-block elements on the same line, regardless of the width of the wrapper, you must reset white-space propertie:

 #wrapper { white-space:nowrap; width:100%; } .child { display:inline-block; white-space:normal; width:100%; } 

updated your fiddle: http://jsfiddle.net/n3e6xzbj/

+1
source

You can try getBoundingClientRect .

The result of this call has a left position, which is probably what you are looking for.

0
source

All Articles