What is the best way to navigate through a div in my particular situation?

I am currently working on a unique feature where users can click on the left navigation link and the right section will automatically scroll to the corresponding box.

For instance, if a user clicks on the second link in the navigation, the right-side div will smoothly scroll to reveal the contents of the second box within that div.

Below is the HTML structure for this feature:

<div id='nav'>
   <ul>
     <li><a id='link1' class='link' href='#'>test 1</a><li>
     <li><a id='link2' href='#'>test 2</a><li>
     ...
     <li><a id='link16' href='#'>test 16</a><li>
  </ul>
</div>

<div id='items'>
    <div id='link1-test' class='box'>
        test 1
     </div>
    <div id='link2-test' class='box'>
        test 2
     </div>
   ...
     <div id='link16-test' class='box'>
        test 16
     </div>
</div>

This is the JavaScript code used for achieving this functionality:

$('#nav a').on('click', function(){

    var id=$(this).attr('id')
    alert(id)

$('#items').animate({
      scrollTop: $('#'+id+'-test').offset().top
           }, 700);      
    })

You can check out a live example of this code here.

I have encountered an issue with the positioning of the boxes inside the right div, as it keeps changing dynamically. I would appreciate any help or suggestions on how to tackle this problem effectively. Thank you in advance!

Answer №1

When scrolling the parent div, the position of each nested div changes. To account for this, you simply need to adjust the offset by calculating the target div's offset and adding the current scroll position of the parent div. By making a single line change in your code, everything will function correctly. Update the scrollTop option for the animate method from:

scrollTop: $('#'+id+'-test').offset().top

to:

scrollTop: $('#'+id+'-test').offset().top + $('#items').scrollTop()

For a demonstration, check out this functional example: http://jsfiddle.net/BPB7z/7/

Answer №2

Check out this link for a demonstration of varying div heights: http://jsbin.com/iZUVoBux/1/edit. You may notice that using .position().top to determine the offset can lead to inconsistencies when the div is scrolled.

function calculatePosition(el) {
  var _x = 0;
  var _y = 0;
  while (el && !isNaN(el.offsetLeft) && !isNaN(el.offsetTop)) {
    _x += el.offsetLeft - el.scrollLeft;
    _y += el.offsetTop - el.scrollTop;
    el = el.offsetParent;
  }
   return {
      top: _y,
      left: _x
  };
}


$('#nav a').on('click', function () {
   $('#items').animate({
      scrollTop: calculatePosition($('#' + this.id + '-test').get()[0]).top
   }, 700);
});

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

Tips for wrapping text around an image using Bootstrap 5

I am having trouble getting my text to wrap around an image using the Bootstrap 5 grid system. I've attempted to use 'float: right' on the image, but it hasn't produced the desired result. The text should flow naturally around the imag ...

"Flask: Dealing with 404 Error when Loading CSS Files

Ensuring that elements are styled properly on my Flask-based website has been a challenge as the css files seem to never load correctly. A peculiar issue arises where the css files will load successfully when initially called from layout.html using the pa ...

24-hour flatpickr timepicker

Can anyone assist me in setting my hour format to 24 hours instead of AM/PM in Angular? I've been struggling with it for the past 2 days. Below are my TypeScript and HTML code snippets: TypeScript: flatpickrOptions: any = { locale: French, enable ...

Simply by loading Bootstrap, it is causing the animation parameters to become disrupted

Currently, I am experimenting with implementing a frontend code I discovered online for simulating a dice roll. If you are interested, you can find the code in this repository: https://codesandbox.io/s/xjk3xqnprw?file=/styles.css:0-4535 Here is the HTML ...

The issue of JQuery $(this) malfunctioning when used within a function parameter

Encountering an issue with the code snippet below: $(".countdown").circularCountdown({ startDate:$(this).attr('data-start'), endDate:$(this).attr('data-end'), timeZone:$(this).attr("timezone") }); On the contrary, the co ...

Automatically filling in related information in multiple input fields after choosing a value in a specific input field using JavaScript

My horizontal form is dynamically generated using JavaScript, with each input field having a jQuery autocomplete that retrieves data from a database using the $.get method. I'm looking to automatically populate the second input field with the corresp ...

Issues with getting full HTML content using selenium for web scraping

My task is to extract the discounted price of a product from a specific website. Upon inspecting the website, I found the following HTML structure: https://i.sstatic.net/LerWE.png This is what my code currently looks like: browser = webdriver.Chrome(exe ...

The getElementByID function functions properly in Firefox but does encounter issues in Internet Explorer and Chrome

function switchVideo() { let selectedIndex = document.myvid1.vid_select.selectedIndex; let videoSelect = document.myvid1.vid_select.options[selectedIndex].value; document.getElementById("video").src = videoSelect; } <form name="myvid1"> <s ...

Increasing space at the top with heading

As I scroll down, the header on my website remains in a static position and disappears. However, when I scroll back up, the header reappears wherever the user is on the page. While this functionality works well, I have noticed that as I scroll all the way ...

Having difficulty accessing the live server on VS Code for download

I'm having trouble installing the live server extension in my VS Code. When I search for "live server" in the extensions marketplace, I can't seem to find it among the results. Can someone please suggest an alternative method for installation? ...

A guide on implementing Mail Merge Template files in PHP

I am new to mail merge and I'm not sure if it's even possible. I have created a template in mail merge, but I don't know how to use PHP to send emails to a list of clients like an RSS feed. Can someone confirm if this is feasible and provide ...

select specific region within image

I'm currently working on cropping an image and sending the cropped data to the server side. To achieve this, I am utilizing the imgareaselect plugin. While I am able to obtain the coordinates of the selection, I am facing challenges in actually croppi ...

Alter the color scheme using jQuery

Exploring the world of websites, I've come across many with a unique color switch feature. Users have the ability to choose a color, and the entire page transforms to match their selection. Check out these links for some examples... http://csmthe ...

Error retrieving resource: server returned a 404 status code indicating file not found for javaScript and CSS files

I can't seem to get my css and js files to load on the server. Here is how my file structure looks like: GAME_Folder https://i.sstatic.net/wzfB3.png HTML doctype html head link(href='https://fonts.googleapis.com/css2?family=Press+Start+2P& ...

Python Script for Automated Download of PDF Files within JQueryFileTree

I am working on a project to automatically download PDF files from a website associated with my employer's company. These PDF files are organized within a JQueryFileTree structure. Is there a way for me to download an entire folder along with its cont ...

Steps to make a sliding tab

I am currently faced with the challenge of coding the support tab on the right side of this page - . The tab currently slides out when clicked. I found the current tab slide-out effect here: My goal is to have both the main tab and the side tab appear wh ...

Unable to interpret JSON data using jQuery's parseJSON function

Currently, I am attempting to execute server operations using AJAX jQuery(document).on('click','a.edit', function (e) { var id=$(this).prop('id'); var params="id="+id; $.ajax({ ...

Validation of forms using Javascript

I currently have an HTML form with JavaScript validation. Instead of displaying error messages in a popup using the alert command, how can I show them next to the text boxes? Here is my current code: if (document.gfiDownloadForm.txtFirstName.value == &ap ...

Creating a user-friendly error message on the interface using JavaScript

I have implemented a table that showcases data from the Geonames API. Currently, I am working on creating a function to handle errors when the user forgets to fill in the input fields and then trigger an alert on the interface. The code snippet below sho ...

Website errors appear on the hosted page in <body> section without being present in the code

Hello there, I have set up a debug website using my "Olimex ESP-32 POE" to send internal data via JSON, eliminating the need for Serial Output from the Arduino IDE (the reasons behind this are not relevant). #include "Arduino.h" #include <WiF ...