jQuery for creating single-page websites with horizontal scrolling navigation

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?

Answer №1

Are you seeking this specific solution?

$('.scroll-trigger').each(function(index){
  $(this).on('click',function(e) {
    var $this = $(this);
    var $anchor = $this.attr('href');
    var $container = $this.attr('data-container');
    var elem = $($anchor);
    var offset = (elem.offset().left - elem.offsetParent().offset().left); 

    if(offset >= 0){
      $($container).animate({'scrollLeft' : offset * index},200);
    }else{
      $($container).animate({'scrollLeft' : offset * -index},200);
    }
    e.preventDefault();
  });                      
})
#pages{
  position: relative;
  overflow-x: hidden;
  white-space: nowrap;
  width: 100%;
  border:1px solid #565656;
}
#pages>section {
  display: inline-block;
  width: 100%;
}
<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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

SQL update query executed through PHP will only modify the value in the first row

I have encountered an issue with my script. I have a table where I retrieve values from a database and display them in an HTML table using PHP. Additionally, I have JavaScript code that displays an HTML form below each row of the table. One important note ...

Adjusting Image Size According to Window Resize?

My current issue involves having four images displayed side by side. When the window size is adjusted or viewed on a smaller device, the layout shifts to a line jump (with three images in a row and the fourth one below). What I actually want is for all fou ...

Send all state values to the child component

I have an old application that sends a JSON to generate a multi-page form. I'm working on creating a universal multi-page form component where we can simply input a JSON to produce a form. The app utilizes a function called buildFormState which initi ...

Tips for ensuring that content doesn't shift down when clicking a drop-down menu

I currently have three dropdowns that function as an accordion. When I click on one dropdown, the rest of the content below shifts down, which is not the behavior I want. Is there a way to prevent the content below each dropdown from moving when a dropdow ...

Obtaining the node generated from a document fragment

Suppose I add a document fragment to the DOM in the following way: const ul = document.querySelector("ul"); const fruits = ["Apple", "Orange", "Banana", "Melon"]; const fragment = new DocumentFragment(); ...

How can I automatically disable certain checkboxes when a specific radio button is selected?

Looking to disable certain checkboxes when a specific radio button is selected. For instance, selecting the first radio button with the id="pz1" should disable checkboxes with matching id values from the thisToppings array. Each radio button cor ...

Automatically open Bootstrap dropdown upon loading the page

Displayed below is my dropdown menu styled using bootstrap: <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="#" id="posuvnik">15min <strong class="caret"></strong></a> <ul class="dropd ...

Improved Node.js algorithm designed to identify anagrams of a specific string in an array. The approach must not rely on generating all possible subsets to find the anagram of the string

I am looking to create a collection of anagram pairs within an array. The input will consist of the initial array of strings. For example: let inputArray = ["abcd", "dbac", "adfs", "adsf", "bDca"]; This program should consider the case of the letters, m ...

What is the reason why an inline-block does not appear to be "visible"?

Does using inline-block cause elements to not be selected by the ":visible" selector? $('body').append($('<p>').css('display', 'inline-block')) var p = $('p'); p.is(':visible'); ==> fals ...

Exploring the Power of AJAX in jQuery Mobile

Although the ajax function in jQuery Mobile is returning the proper data, I'm facing an issue where the element styles cannot be applied to the returned data. function feedsearch() { $.ajax ({ url: "feed.php", cache: false, type:"get" ...

Utilizing a combination of PHP and jQuery, certain checkbox options were dynamically deactivated

<input type="checkbox" name="pref[]" value="red//fuji" />Fuji <input type="checkbox" name="pref[]" value="red//pinklady" />Pink Lady <input type="checkbox" name="pref[]" value="red//reddelicious" />Red Delicious <input type="checkbox" ...

Disregard the JSON formatting and extract solely the values

After extracting data from an API, the format of the returned information looks like this: [{"id":21},{"id":22},{"id":24}] Next, I need to send this data to a database using a different API. However, the format for sending should be like this: [21,22,24] ...

experiencing a problem with the older version 1.5 of the swfobject.js software

Hello there! I am encountering an issue with swfobject.js version 1.5 specifically in IE7 and IE8. My chart is not displaying in these web browsers, but it works perfectly fine on Chrome, Firefox, and even IE 6. Do you have any suggestions on how to resolv ...

How can we effectively transform an HTML opening and closing tag into a function?

Dealing with a complex HTML tag can be challenging, especially when it appears in various parts of the code. For instance: <div class="blabla" data-test="blablabla" ... data-another-attribute="blabla" > <some complex html code ... > </ ...

Is it possible to execute a controller function only when the textarea has completely loaded?

My current setup includes a textarea as shown below: <textarea rows="3" maxlength="144" ng-maxlength="144" type="text" name="testPost" id="testPost_{{item.id}}" ng-init="focusText('testPost', item.id)" ng-model=" ...

What is the best way to showcase a person's first and last name in individual text fields?

Within a drop-down menu, each option is formatted like the following example: scomp23 - Jack Turner By utilizing the code snippet below: var text = $(this).find('option:selected').text(); var split = text.split(' - '); $('#curre ...

Use Onblur and Onfocus events in an input field that is read-only

Here is an input field: <input class="" type="text" id="Name_11_1" name="Name" value="Your name:"> I would like to modify it as follows: <input class="" type="text" id="Na ...

What is the reason for the absence of the $.ajax function in the jQuery package designed for node.js?

Here is my code sample, which I would like to use for practicing with jQuery's ajax function. Note that I have already installed the jQuery package using npm install jquery: var $ = require('jquery'); var remoteValue = false; var doSometh ...

Different or improved strategy for conditional rendering in Angular

Hey there! I've got a few *NgIf conditions in my template that determine which components (different types of forms) are displayed/rendered. For example, in one of my functions (shown below) private _onClick(cell:any){ this._enableView = fals ...

How can I make a layer visible in OpenLayers?

I can't figure out what I'm doing wrong. I believe everything is written correctly: The HTML code I have looks like this: <b>&nbspSelect Area</b> <select id="mySelect_1" onchange="showSelectedArea();" > <op ...