Here's my situation. I've created several panels stacked side by side which are wrapped in a main container. Each panel takes 100% the viewport width and height. My goal is to be able to scroll horizontally to each panel when I click on their respective link. This works fine using a pure css approach. However, I'm learning jQuery and I wish to use the .scrollTo() method to achieve this.
When the panels were stacked one below the other (i.e vertically), I was able to obtain the top offset of each panel and scroll to their position nicely.
With the horizontal variation, I'm having troubles to obtain the left offset of the panels. I get a left offset of zero for all of them. If my logic is right, say the viewport is 1920px wide, the 2nd panel's left offset should be at 1920px, the 3rd at 3840px etc.
From the information I've gathered so far, it's because the panels are outside the viewport. And indeed, I've applied a width of 20% to the panels so that they were all visible in the viewport then I tried to alert their left offset. They were prompted to me successfully.
So how do I get around this issue ? It might seem like I'm reinventing the wheel but like I said, I'm learning jQuery so I need to understand why it's behaving as such and how I can solve this. Any help will be highly appreciated :) Below are snippets of what I have so far.
Thanks.
The 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>
The CSS:
.mainWrapper, .panel {
position: relative;
height: 100%;
}
.mainWrapper {
top: 0;
left: 0;
}
.panel {
display: inline-block;
background: rgba(255, 255, 255, 1);
}
The 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's not working
$panelScrollPos[i] = Math.round($(this).offset().left - $panelWrapper.offset().left);
alert('Panels position are: ' + $panelScrollPos[i]);
});
});
Please note that I have used .width() method to set the width of .mainWrapper and .panel elements. I haven't included it in the snippet as it is working.
to be able to set your inline-block
elements on a single line , no matter the width of the wrapper you should reset the white-space
propertie:
#wrapper {
white-space:nowrap;
width:100%;
}
.child {
display:inline-block;
white-space:normal;
width:100%;
}
your fiddle updated : http://jsfiddle.net/n3e6xzbj/
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