I'm attempting to implement a horizontal scrolling section on my webpage.
Although this is a basic function that I have successfully executed multiple times in the past, I seem to be overlooking something rather obvious.
There seems to be an issue with the offset value after each click.
$('a.scroll-trigger').click(function(e) {
var $this = $(this);
var $anchor = $($this.attr('href'));
var $container = $($this.attr('data-container'));
var offset = $anchor.offset().left;
$container.scrollLeft(offset);
e.preventDefault();
});
#pages {
overflow-x: hidden;
white-space: nowrap;
}
#pages>section {
display: inline-block;
width: 768px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li><a class="scroll-trigger" href="#section1" data-container="#pages">Section 1</a></li>
<li><a class="scroll-trigger" href="#section2" data-container="#pages">Section 2</a></li>
<li><a class="scroll-trigger" href="#section3" data-container="#pages">Section 3</a></li>
</ul>
<!-- pages is nested in a container with a maximum width of 768px. -->
<div id="pages">
<section id="section1">
<h2>Section 1</h2>
</section>
<section id="section2">
<h2>Section 2</h2>
</section>
<section id="section3">
<h2>Section 3</h2>
</section>
</div>
The current setup is not functioning as intended. The offset
variable is inconsistently calculated.
Do you have any suggestions or solutions?