What is the best way to use scrollIntoView() to display an additional item at the top or bottom of the visible area

When implementing scrollIntoView() with navigation buttons (up and down), I aim to display two items at a time to signal to the user that there are more items to navigate. However, the first and last items should retain their default behavior so the user understands it is the end of the list.

You can refer to this image for clarification: https://i.stack.imgur.com/zoerG.jpg

Below is the code snippet:

*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: sans-serif;
}
.myList{
    width: 100px;
    height: 100px;
    margin: 5px;
    overflow: scroll;
    display: flex;
    flex-direction: column;
    background-color: gray;
    list-style: none;
}
button{
    width: 40px;
    margin: 0 5px;
}
.myList>*{
    display: block;
    padding: 5px;
}

.focused{
    background-color: yellow;
    color: black;
}
<html>
  <body>
    <ul class="myList">
      <li data-nav="0">Item 1</li>
      <li data-nav="1">Item 2</li>
      <li data-nav="2">Item 3</li>
      <li data-nav="3">Item 4</li>
      <li data-nav="4">Item 5</li>
      <li data-nav="5">Item 6</li>
      <li data-nav="6">Item 7</li>
    </ul>
    <button onclick="move(true)">UP</button>
    <button onclick="move(false)">down</button>
    
    <script>
        let nav = document.querySelectorAll("[data-nav]");
        nav.forEach(el=>{
            el.classList.remove("focused");
        })
        nav[0].classList.add("focused");

        let focusedIndex = 0;
        function move(dir){
            if(dir && focusedIndex > 0) focusedIndex--;
            else if(!dir && focusedIndex < 6) focusedIndex++;
            nav.forEach(elem =>{
                elem.classList.remove("focused");
            })
            nav[focusedIndex].classList.add("focused");
            nav[focusedIndex].scrollIntoView(true);
        }
    </script>
  </body>
</html>

Answer №1

When the previous element appears, follow these steps:

  • If we click the up button and the current index is not the first element, we should scroll to the previous element and add a focused class to the current element.

let nav = document.querySelectorAll("[data-nav]");
            nav.forEach((el) => {
                el.classList.remove("focused");
            });
            nav[0].classList.add("focused");

            let focusedIndex = 0;
            function move(dir) {
                if (dir && focusedIndex > 0) focusedIndex--;
                else if (!dir && focusedIndex < 6) focusedIndex++;
                nav.forEach((elem) => {
                    elem.classList.remove("focused");
                });
                /*
                check if we click in up button and will not arrive to last one
                [1] add foucs to current index
                [2] scroll to prev current index
                */
                if(dir && nav[focusedIndex].dataset.nav != 0) {
                    nav[focusedIndex].classList.add("focused");
                    nav[focusedIndex-1].scrollIntoView(true);
                }
                /*
                    if we click in down button dont do any thing differnt because we already can see 
                    another items or the first condition return flase because this already the 
                    first element
                */
                else {
                    nav[focusedIndex].classList.add("focused");
                    nav[focusedIndex].scrollIntoView(true);
                }

            }

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

What is the best way to duplicate a CSS shape across a horizontal axis?

I am working on decorating the bottom of my page with a repeated triangle design. The image provided only displays one triangle, but I would like to extend it across the entire horizontal div. Here is a screenshot of my progress so far: https://i.stack.im ...

Unable to modify the .top attribute style in elements within an arraylist using JavaScript

I need to align multiple images in DIVs on the same line by setting their Top value to match the first image in the array. Here is the code I am struggling with: (addBorder function is called when divs are clicked) <div class="DRAGGABLE ui-widget-cont ...

The MatTableDataSource provides a promise that includes approximately 7000 rows of data

When attempting to load a large amount of data into a MatTableDataSource, I am facing an issue. I would like to display a loader until the data is fully set, but I am unsure of when that happens. I attempted to use a promise like this: return new Promise(r ...

Initiate monitoring for child component modifications

I'm looking to disable 'changeDetection' for the parent component while enabling it for the child component. Can you provide an example of how this can be achieved? The parent component contains static data, meaning change detection is not ...

Ways to retrieve "this" while utilizing a service for handling HTTP response errors

I have a basic notification system in place: @Injectable({ providedIn: 'root', }) export class NotificationService { constructor(private snackBar: MatSnackBar) {} public showNotification(message: string, style: string = 'success' ...

A method to transfer a floating point number from Python to JavaScript without using cgi

Running an Apache server from a Raspberry Pi, I have a Python script that prints sensor input to the console. A PHP script then processes this output and controls a light based on the sensor reading before printing it again. Everything works fine when exec ...

Creating multiple asynchronous calls within a loop in JavaScript

I am currently working on a task in my gulpfile.js that involves uploading an app using Gulp and SharePoint. 'use strict'; const gulp = require('gulp'); const build = require('@microsoft/sp-build-web'); const spsync = require ...

Match the test choices with the corresponding `radio` buttons

Looking for help with my quiz application. How can I align text vertically with radio buttons? Take a look at the code here on Codepen. One issue I'm facing is the alignment of long label texts, particularly in questions 9, 12 & 14. I've tried va ...

tips for implementing JSON loading in Ext JS

While attempting to load values from a web service, I encountered the following error message: "ChatStore.data.items[i] is undefined." The mapping code for extjs is as follows: ChatStore = new Ext.data.JsonStore({ storeId: 'ChatStore1' ...

What are some ways to utilize symbol fonts such as marvosym within a web browser?

Are you looking to use special LaTeX fonts like \Pluto from marvosym in your web development projects? Wondering how to display this symbol with HTML / JavaScript / CSS without relying on an image? You can download the font from This symbol corresp ...

Error animation on client-side validation not resetting correctly

Incorporated a form validation and error display system utilizing TransitionGroup for animations. The flag issueVisible manages the visibility of the error message, while determineField() aids in identifying the field related to the error. The issue arise ...

I am attempting to send an array as parameters in an httpservice request, but the parameters are being evaluated as an empty array

Trying to upload multiple images involves converting the image into a base64 encoded string and storing its metadata with an array. The reference to the image path is stored in the database, so the functionality is written in the backend for insertion. Ho ...

Execute a function singularly upon vertical scrolling upwards or downwards

Looking for a solution to load two distinct animated graphics on a website when scrolling up or down, I managed to trigger the desired functions. However, there seems to be a bug where the functions are being triggered excessively: $(window).scroll(func ...

Error 16 occurred when attempting to ngUpgrade two different versions of Highcharts

After successfully upgrading my app to use ngUpgrade, I encountered an issue while trying to incorporate Highcharts. In the original version of the app, there was an older version of Highcharts designed for AngularJS. However, in the new hybrid app using ...

Divide the string into several segments according to its position value

Here is a piece of text that I would like to divide into multiple sections, determined by the offset and length. If you have any questions or comments and would like to get in touch with ABC, please go to our customer support page. Below is a function ...

Only initiate an AJAX call if there are no other pending AJAX requests from prior function invocations

Arriving at a new, chaotic code base with no testing available has presented me with a significant challenge. I am currently struggling to resolve an issue without the use of ES6, only relying on plain vanilla JS and jQuery. The scenario: Within a web pag ...

Managing the "Accept Cookies" notification using Selenium in JavaScript

As I use Selenium to log in and send messages on a specific website, I am faced with a cookie popup that appears each time. Unfortunately, clicking the accept button to proceed seems to be quite challenging for me. Here is an image of the cookie popup Th ...

How can I customize the appearance of the container and items in a dropdown <select> menu?

Im using contact form 7 on wordpress, i don't want to use a plugin rather use plain css/js to bring the results if possible. Something like this : https://i.stack.imgur.com/VTWRg.jpg ...

Adjusting the height of a flexbox column to fit three rows within the space of two

Exploring the wonders of Flexbox and delving into its functionality. I have shared a Code Sandbox link showcasing my React /bootstrap code in progress... Currently, I am developing a clock component with two buttons for adjusting time (increase/decrease). ...

What could be the reason my Bootstrap 5 dropdown menu is not functioning correctly?

As of late, I've delved into web development and have been utilizing Bootstrap v5.0 for creating a website. The code below is from a file named "grage.php": <!-- HERE SHOULD BE THE CODE OF GARAGE --> <div class="container-fluid" ...