What measures can be taken to ensure that scrollIntoView does not interrupt when the user begins scrolling on their own?

I have a navigation bar where I am using the scrollIntoView method to ensure that the active element is always centered in the list. However, I encountered an issue wherein scrolling the main content interrupts or stops the scroll action triggered by scrollIntoView. This behavior only occurs when the user is actively scrolling. You can view an example of this scenario here: https://jsfiddle.net/2otv6pyx/ (The code remains the same as provided below. The issue can be observed more clearly on stackoverflow due to page scrolling)

const first = document.querySelector('#first')
const last = document.querySelector('#last')
let atLast = false
setInterval(() => {
  if (!atLast) {
    last.scrollIntoView({
      block: "end",
      behavior: "smooth"
    })
    atLast = true
  } else {
    first.scrollIntoView({
      block: "end",
      behavior: "smooth"
    })
    atLast = false
  }
}, 1000)
nav {
  position: sticky;
  top: 0;
  background-color: white;
}

nav>ul {
  list-style-type: none;
  display: grid;
  grid-auto-flow: column;
  overflow-x: scroll;
}

nav .active {
  color: red
}

nav li {
  padding-right: 1rem;
}
...

<main>
  ...
</main>

I am looking for a solution that would allow the main content to be scrolled without interfering with the navbar animation. Is there a way to enforce the scrollIntoView function despite user scrolling?

Additionally, I have observed that when I scroll the entire content downward, it initially scrolls upward and then horizontally.

Answer №1

Your code is facing a major issue with the functionality of the Element.scrollIntoView method as it inadvertently scrolls the entire window instead of just the targeted ul element.

For a more precise scrolling experience, you should consider utilizing the Element.scrollTo method which allows you to specifically scroll within the desired element without affecting the overall window scroll behavior.

When implementing the .scrollTo method, it's crucial to specify the exact position for scrolling. Instead of using fixed values like left: 0 or left: someBigNumber, dynamic calculation of scroll points is highly recommended to achieve optimal results.

To accurately determine the scroll point on the horizontal axis (left value), adjustments need to be made considering the perspective difference between the window and the target ul element containing the necessary elements.

It's worth noting that due to certain limitations, reaching the extreme left might not be possible when scrolling the last element into view at the beginning. This phenomenon occurs because there could be empty space before the first visible element in the view.

During testing, several improvements were made including adding semicolons to statements, replacing setInterval with an async function coupled with a while loop for better readability, and making enhancements to the CSS styling of the navigation area.

// Revised JavaScript Code
const first = document.querySelector('li:first-of-type');
const last = document.querySelector('li:last-of-type');
const ul = document.querySelector("ul");

const lastLeft = last.getBoundingClientRect().left;
const firstLeft = first.getBoundingClientRect().left;
const ulLeft = ul.getBoundingClientRect().left;

const wait = () => new Promise(r => setTimeout(r, 2000));

(async () => {
  await wait();
  while(true) {
    ul.scrollTo({
      behavior: "smooth",
      left: lastLeft - ulLeft
    });
    await wait();
    ul.scrollTo({
      behavior: "smooth",
      left: firstLeft - ulLeft
    });
    await wait();
  }
})();
// Updated CSS Styling
nav {
  position: sticky;
  top: 0;
  background-color: white;
}

nav>ul {
  list-style-type: none;
  display: grid;
  grid-auto-flow: column;
  overflow-x: scroll;
}

nav .active {
  color: red
}

nav li {
  padding-right: 1rem;
}

p {
  line-height: 8rem;
}
<nav>
  <ul>
    // Sample List Items...
  </ul>
</nav>

<main>
  <p>Lorem ipsum dolor sit amet...</p>
  <p>More Lorem ipsum content...</p>
</main>

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

Steps for extracting all query parameters from a URL containing a redirect URL as one of the parameters

Below is the code snippet I am currently using to extract query parameters from the application URL. However, this logic fails when a URL is passed as a query param which includes its own query parameters. For example: Example: In this scenario, url2para ...

trouble concerning the responsiveness of a jQuery popup

Hello, I am trying to create a responsive login popup using jQuery but have been struggling for a week. Below is the code snippet that I have been working on. Any help or guidance would be greatly appreciated. //scriptLogin.js archive $(document).ready ...

Reloading a Nuxt.js page triggers the fetch function

I'm facing an issue with nuxt.js fetch(). Whenever I reload the page, it does not fetch the data again. It only fetches if I come from a router link. How can I force it to actually refetch the data from my API? export default { async fetch() { ...

Adjust the object size to match the Viewport dimensions

I've been developing a VR world where the camera can be turned and tilted in the center but not moved around freely. Within this virtual reality environment, you have the ability to attach a video to the background. Users can either play it by clicki ...

Switch webpage HTML content to XLS format

Hey folks, I'm a bit uncertain about my client's requirements but thought sparking a conversation might help. My client is looking to extract HTML data from a webpage and convert it into an XLS format. The content is all sourced from their own w ...

Generate a spreadsheet file in xlsx format by using the exceljs library in Node

I am currently working with exceljs 3.8 in an attempt to generate a new XLSX file, but unfortunately the code below seems to be malfunctioning. createNewExcelFile: function (excelFilePath) { //excelFilePath: Path and filename for the Exce ...

Creating a unique HTML id using an evaluated expression

My goal was to create a minimalist version of the classic game "tic tac toe" using AngularJS. To achieve this, I had to come up with a unique solution by assigning each button a distinct ID (f+i). HTML <table> <tr ng-repeat="f in [5,10,15]"& ...

Fragment with HTML embedding for full screen video display in web view

Hello everyone, I have a question about enabling full-screen support for HTML embedded videos in my webview. I have set hardware acceleration to true in the manifest and the video plays fine, but when I try to go fullscreen, the video stops. Here is my co ...

Error: A SyntaxError was encountered due to a missing closing parenthesis after an argument list while writing JavaScript within PHP code

I'm facing an issue writing JavaScript within PHP code. Here's my script : echo ' <script>'; echo ' $(function(){'; echo ' x = parseInt($("#counter2").val());'; echo ' $("#add_row2").click(function(){&apo ...

Arranging by upcoming birthday dates

Creating a birthday reminder app has been my latest project, where I store names and birthdays in JSON format. My goal is to display the names sorted based on whose birthday is approaching next. Initially, I considered calculating the time until each pers ...

What is the best way to eliminate a CSS style from a div?

I have implemented jQuery Autosize to automatically adjust the height of textarea elements. It works perfectly when I focus on the textarea element. However, when I blur out of the textarea, I want to reset the height to its default value. I am unsure of ...

Developing a multi-graph by utilizing several JSON array datasets

Currently exploring D3 and experimenting with creating a multi-line graph without utilizing CSV, TSV, or similar data formats. The key focus is on iterating over an array of datasets (which are arrays of objects {data:blah, price:bleh}). I am trying to a ...

At times, the Kendo UI Tooltip may linger on screen longer than expected, failing to disappear as

I've been experimenting with this issue for quite some time now, but I'm stumped. Whenever I quickly move my mouse cursor over a series of links, occasionally a tooltip will linger on the screen even after the cursor has moved away from the link. ...

What is the best way to establish and maintain lasting connections with the Firebase database while utilizing the superagent

Currently, I am following the Firebase Functions documentation on enhancing Firebase database performance. I have provided the code snippet below for your reference. const request = require('superagent'); const functions = require('fireba ...

What is the best way to remove specific items from an AngularJS ng-repeat loop?

Is there a way to filter out certain items in an ng-repeat loop? For instance, consider the following simplified code snippet: <div class="row" data-ng-repeat="entry in data.feed.entry | orderBy:'gsx$timestamp.$t':true"> {{entry.gsx$jobID ...

Unable to interpret Python/Django-generated JSON object on client side

I'm encountering an issue while passing a data object from a Python/Django application to the frontend using AJAX in JSON format. Despite everything appearing to be functioning correctly, I am unable to properly parse the JSON object within JavaScript ...

Performance issues are being experienced on website for tablet and smartphone usage due to slow loading times

My client's website is running on an old Dell PowerEdge 2600 with Windows Server 2008. While desktop and laptop access to the site is smooth, access from tablets and smartphones is extremely slow, taking over 10 minutes to load or sometimes not loadin ...

The application encountered an exception and has ceased to respond, displaying a custom error page

I have a .NET application running on IIS 7 that is accessed from IE7. When a specific exception occurs, the page is redirected to a plain .htm page with a back button that should take the user back to the previous page. This exception handling is implement ...

Apply a transformation effect to the current active menu item in the Wordpress CSS main navigation

I am currently working on a local WordPress installation with a theme. One specific feature I am trying to achieve is to have a dynamic colored line with a triangle shape indicating the 'current page' on the menu. My goal is to duplicate this tri ...

Setting a fixed data value within a div for subsequent retrieval through a function

I found a helpful example that demonstrates how to convert numbers into words. You can check it out here. The function for converting numbers into words is implemented in the following HTML code: <input type="text" name="number" placeholder="Number OR ...