Determining the exact location of elements within a static div box

I'm facing an issue with navigating between pages on my website. I have a list of pages and links to each page, and I am using the jQuery animate() function along with offset().top value to move to the desired page. However, after the first click, the position is not maintained and strange behavior occurs.

Here is a code snippet demonstrating the problem:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"
integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>
</head>
<body style="margin: 0px; padding: 0px; background-color: #AFAFAF;">
<div style="position: fixed; top: 0; left: 0; background-color: white; width: 100px; height: 120px; z-index: 99">
<a href="#" onclick="goToPage(1);">Go to page 1</a><br>
<a href="#" onclick="goToPage(2);">Go to page 2</a><br>
<a href="#" onclick="goToPage(3);">Go to page 3</a><br>
<a href="#" onclick="goToPage(4);">Go to page 4</a><br>
<a href="#" onclick="goToPage(5);">Go to page 5</a><br>
<a href="#" onclick="goToPage(6);">Go to page 6</a>
</div>
<div id="divContainer">
<div id="fixedContainer" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0;">
<div id="pageContainer"
style="margin: 0 auto; height: 100%; max-width: 800px; position: relative; overflow-y: scroll; transition: all 0.3s ease-out 0s;">
<div id="page1" style="position: relative; height: 1200px; background-color: lightblue;">
</div>
<div id="page2" style="position: relative; height: 1200px; background-color: lightcoral;">
</div>
<div id="page3" style="position: relative; height: 1200px; background-color: lightcyan;">
</div>
<div id="page4" style="position: relative; height: 1200px; background-color: lightgoldenrodyellow;">
</div>
<div id="page5" style="position: relative; height: 1200px; background-color: lightgray;">
</div>
<div id="page6" style="position: relative; height: 1200px; background-color: lightgreen;">
</div>
</div>
</div>
</div>
<script>
function goToPage(elementId) {
$('#pageContainer').animate({
scrollTop: $('#page' + elementId).offset().top
}, 1200);
}
</script>
</body>
</html>

The goal is to smoothly navigate between pages without altering the existing structure.

Answer №1

It is important to utilize the position() method rather than offset(), and it's recommended to do this only once when the page loads.

You can implement it like so:

$("#pageContainer > div").each(function() {
   $(this).attr("offset",$(this).position().top);
})

function goToPage(elementId) {
  $('#pageContainer').animate({
    scrollTop: $('#page' + elementId).attr('offset')
  }, 1200);
}
<html>

<head>
  <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>
</head>

<body style="margin: 0px; padding: 0px; background-color: #AFAFAF;">
  <div style="position: fixed; top: 0; left: 0; background-color: white; width: 100px; height: 120px; z-index: 99">
    <a href="#" onclick="goToPage(1);">Go to page 1</a><br>
    <a href="#" onclick="goToPage(2);">Go to page 2</a><br>
    <a href="#" onclick="goToPage(3);">Go to page 3</a><br>
    <a href="#" onclick="goToPage(4);">Go to page 4</a><br>
    <a href="#" onclick="goToPage(5);">Go to page 5</a><br>
    <a href="#" onclick="goToPage(6);">Go to page 6</a>
  </div>
  <div id="divContainer">
    <div id="fixedContainer" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0;">
      <div id="pageContainer" style="margin: 0 auto; height: 100%; max-width: 800px; position: relative; overflow-y: scroll; transition: all 0.3s ease-out 0s;">
        <div id="page1" style="position: relative; height: 1200px; background-color: lightblue;">
        </div>
        <div id="page2" style="position: relative; height: 1200px; background-color: lightcoral;">
        </div>
        <div id="page3" style="position: relative; height: 1200px; background-color: lightcyan;">
        </div>
        <div id="page4" style="position: relative; height: 1200px; background-color: lightgoldenrodyellow;">
        </div>
        <div id="page5" style="position: relative; height: 1200px; background-color: lightgray;">
        </div>
        <div id="page6" style="position: relative; height: 1200px; background-color: lightgreen;">
        </div>
      </div>
    </div>
  </div>
  <script>
  </script>
</body>

</html>

The .position() method enables us to retrieve an element's current position (specifically its margin box) in relation to the offset parent (specifically its padding box, excluding margins and borders). Unlike .offset(), which retrieves the current position relative to the document, .position() is more useful when positioning a new element near another within the same containing DOM element. source

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

Developing a unique JavaScript object by extracting information from a jQuery AJAX response

Is there a recommended approach for creating a custom JavaScript object that contains data retrieved from a jQuery AJAX request? I'm considering two methods, but unsure which is the most appropriate. The first method involves including the AJAX reques ...

I desire to rearrange the items within several arrays of lists

I currently have an array set up like this 0: (5) ["2", "X", "8", "11", "15"] 1: (5) ["1", "5", "X", "X", "14"] 2: (5) ["X", "4", "7", "10", "13"] 3: (5) ["X", "3", "6", "9", "12"] My goal is to swap the position of the digit 1 with the position of digi ...

How can I ensure the correct order when parsing JSON and performing actions with it?

After fetching JSON data from YQL and converting it into a list, my goal is to highlight specific rows in the list based on their contents. Currently, I can achieve highlighting and toggling separately using .click, but I prefer to skip that step and have ...

Is it possible to have a custom animated hamburger icon closed by default on page load in Bootstrap 4

I'm trying to use the default-toggler for bootstrap in a more traditional way, but I can't seem to understand why my custom changes are causing the button to initially load closed? [Something like ' X '] It's probably just a m ...

Is there a way to halt the execution of code once a dialog box is opened?

Having an issue with my code: $("#lbCreer").click(function (e) { e.preventDefault(); $("input:checked").each(function () { var id = this.value; $("#hdId").val(id); $("#dialog-form").dialog("open"); // Stop the each ...

The close button is not functioning properly

I created a script to close my div element by clicking on the 'x' icon, but instead of deleting the div only, the whole page gets deleted. I'm not sure where I went wrong, can anyone help me? HTML <div class="note"> <span id ...

How to display a div in Angular when hovering with ElementRef and Query List

I am having trouble implementing a ngFor loop in my project where I want to display a div on mouse hover using the @Input notation. This is how my HTML code looks: <div class="col s12 m6" style="position: relative" *ngFor="let res of hostInfo.resident ...

Achieving Vertical Stacking and Responsive Scaling for Row and Column Containers on Mobile View Using HTML, CSS, and Bootstrap 4

Utilizing the Bootstrap grid system to organize text boxes in a 2 by 2 layout on a webpage. The desktop view displays the content in rows and columns effectively, but it would be beneficial to have an easy way to adjust the width. However, the problem ari ...

The button event is unresponsive within the Bootstrap modal

I've been attempting to capture the button click event within a modal, but unfortunately, it's not functioning as expected. Am I overlooking something crucial? Below is the header section of my HTML file, which is built using Django. {% load st ...

Mastering the art of writing protractor scenarios

In a hypothetical scenario where an Angular app consists of two pages - one for contacts (featuring a table with contacts and an "add new contact" button) and another for adding a new contact, the following steps can be outlined: Click on the "add" butto ...

jquery is not providing any text content from the body

My current setup involves an ajax post that sends a website address to PHP for retrieval, and then I want jQuery to locate specific elements within the site and retrieve the text from those elements. While this method works fine for certain elements like h ...

Controlling the HTML5 dialog element within a React application

Struggling to implement a basic configuration dialog with a close icon in the top-right corner using React. In other frameworks, it's easy to show/hide a dialog with .showModal()/close(), but manipulating the DOM directly in React is not recommended. ...

Track and log specific route requests with ExpressJS morgan feature

Hello, I am currently utilizing the NodeJS web framework Expressjs along with a middleware called morgan to log requests to a file. Here is my configuration: // create a write stream (in append mode) var accessLogStream = fs.createWriteStream(__dirname + ...

How can the ChangeDetectorRef be leveraged to identify and respond to changes in component state for seamless integration with the material stepper component

While working with the Angular 8 Material Stepper, I am validating form states and setting stepCompleted to true when the conditions pass. You can view a demo of this functionality on Stackblitz: https://stackblitz.com/edit/angular-mat-stepper-demo-with-f ...

The Label in Material UI TextField is appearing on top of the border,

Incorporating Material UI TextField and Material UI Tab, I have encountered an issue. There are two tabs, each containing a text field. Upon clicking on the TextField, the label's border is supposed to open, but this behavior only occurs if the curren ...

What is the method for assigning a link to a variable in JavaScript?

As I develop a website featuring an HTML course, I've opted for a consistent format for each lesson or page. One detail I've been working on involves setting a link within a button to a variable enclosed in quotes. For instance, I utilize the cod ...

What steps do I need to follow to open a new window in a different web browser?

By adding :target => '_blank' in a Rails view, you can open a new browser tab within the same window like this: <%= link_to 'Dataset', @dataset_url, target: '_blank' %> If you need to open a new window in a complet ...

transferring information between two ajax calls upon completion of the first ajax request

Attempting to pass data to jvectormap from an ajax call, using a when function to ensure the code runs after the ajax call has finished loading. The issue I'm facing is that the map appears empty and I encounter an error. Uncaught ReferenceError: ...

Is there a way to generate inline block elements that occupy the full 100% width? Furthermore, can the second element contain an additional element that is revealed upon

Currently, I am working on a project that involves displaying images with text overlays. The text overlays are designed as inline blocks with varying background colors. One issue I encountered is that there is unwanted whitespace between the background co ...

What is the most efficient method for defining a string structure in TypeScript?

Consider the following example of a JavaScript object: const myObject = { id: 'my_id', // Base value which sets the structure for the following values (always pascal case). upperID: 'MY_ID', // Uppercase version of `id`. camel ...