Automated scrolling within a div when an li element overflows

Looking to implement automatic scrolling in a div. I have a list of elements within a fixed height div, and now I want the div to scroll automatically when I press the down key after highlighting the 3rd li element (i.e Compt0005). Can anyone help me solve this?

Demo:- Check it out here

Answer №1

This block of code demonstrates how to manipulate the scrollTop property of a div element using the .getBoundingClientRect() method.

$(function () {
    var liPosition = 0;
    var items = $("#ulSearch li");
    var divSearchContent = $("#divSearchContent");
    divSearchContent.hide();
    $("#txtSearch").keydown(function (e) {
        if (e.keyCode == 13) { // check for enter key press
            $("#txtSearch").val(items.eq(liPosition).text());
            divSearchContent.hide();
            return;
        }
        if (e.keyCode != 38 && e.keyCode != 40) { // check for up and down arrow keys
            return;
        }
        divSearchContent.show();
        items.eq(liPosition).css("background-color", "");
        if (e.keyCode == 40 && liPosition < items.length - 1) { // handle down arrow key
            liPosition++;
        }
        if (e.keyCode == 38 && liPosition > 0) { // handle up arrow key
            liPosition--;
        }
        items.eq(liPosition).css("background-color", "red");
        var b1 = divSearchContent[0].getBoundingClientRect();
        var b2 = items.eq(liPosition)[0].getBoundingClientRect();
        if (b1.top > b2.top) {
            divSearchContent.scrollTop(divSearchContent.scrollTop() - b1.top + b2.top);
        }
        else if (b1.bottom < b2.bottom) {
            divSearchContent.scrollTop(divSearchContent.scrollTop() - b1.bottom + b2.bottom);
        }
    });
});

JSFiddle

Answer №2

modify each instance of

$("#ulSearch li:eq(" + liPossition + ")").css("background-color", "red")

to

 $("#ulSearch li:eq(" + liPossition + ")").css("background-color", "red")[0].scrollIntoView();

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

The JQuery script functions properly when directly embedded in an HTML file, but fails to work when linked from an external file

While I'm working on some code using JQuery's .hover method, I've encountered an interesting issue. It seems to work fine when written directly in the main HTML file index.html, but for some reason, it fails to execute when written in a Java ...

The send_keys() function in Selenium version 3.141.0 works perfectly on Windows, but unfortunately, it is not functioning correctly on Linux Debian 11

I've been experimenting with web automation using Selenium. Everything was running smoothly until I updated my packages - now the send_keys() method isn't functioning on Linux, but it's working fine on Windows with the same versions. I&apo ...

Tips for verifying a login modal on an asp.net webforms using jQuery?

I am currently working on an asp.net webpage that utilizes a modal bootstrap for user login. Upon clicking the Login button, it should authenticate the user and initiate a server-side method called "ExportToZip" to download a zip file. My issue lies in ens ...

Use percentages for the width in CSS and pixels for the height, ensuring that both dimensions are equal

I'm attempting to create a square that adjusts its size according to the screen size. Currently, I have the width set to 25%. Is there a way to ensure that the height remains the same length in pixels as the width? Appreciate any assistance on this ...

Switching between vertical and horizontal div layouts while reorganizing text fields within the top div

function toggleDivs() { var container = document.querySelector(".container"); var top = document.querySelector(".top"); var bottom = document.querySelector(".bottom"); if (container.style.flexDirection === "column") { container.style.flexDirec ...

D3 and dimple line graphs

As I continue to explore D3, I am working on a project where I need to display data using the Dimple module for charting. The user should also have the ability to add parameters. I have experimented with two different ways of formatting my data, and I hav ...

Replace all anchor tags containing href="#" with the Javascript function Void(0) using jQuery

Currently, I am attempting to update all anchor tags using href="#" and changing the value to JavaScript:Void(0) instead of just # running throughout the entire application. However, it seems that this change is being applied to all anchor tags, even tho ...

Updating an HTML input field property with JavaScript is not reflecting the changes

I am currently working on a form with two fields: stationery type and stationery request quantity. The stationery request quantity field only accepts numerical input. The minimum quantity that can be entered in this field depends on the value selected in t ...

Show or hide a div based on the visibility of another div in Angular using *ngIf

Looking for a way to dynamically display images based on the visibility of another image? Consider the code snippet below: <div *ngFor="let badge of user.progress.unlockedBadges"> <img id="{{i}}_unlockedImage" *ngIf="badge == achievemen ...

Javascript: Iterating over a promise contained in an object

Currently, I am attempting to iterate through a return from an API that supposedly contains an object with a promise within it. You can find the API documentation here: https://github.com/sentanos/roblox-js/wiki/Main-Functions This is what my code looks ...

Challenges arise when using two side-by divs with a 100% height

Caution: This page may include NSFW images. I am attempting to set the left div to a width of 300px and have the right one fill the remaining space on the page. After finally getting them to sit side by side, I encountered some strange height issues due ...

Tips for relocating a div panel below all other div panels when a button is clicked with JQuery and CSS

There are several panels stacked below each other. Each panel has a button that, when clicked by the user, should move the panel to the bottom of the stack. For example: If there are 10 panels aligned sequentially and the user wants to remove Panel 2 by ...

react component fails to rerender upon state change

I am struggling with a React functional component that includes a file input. Despite selecting a file, the text in the h1 tag does not change from choose file to test. The handleChange function is triggered successfully. A console.log statement confirm ...

random mongoose response 500

I came across a nodeJS code recently that was supposed to retrieve random documents from my mongoose collection using the mongoose-random plugin. However, whenever I call the findRandom() method, it returns a 500 error. test.js Below is the code snippet: ...

Struggling to figure out how to make Bootstrap toast close or autohide properly

Looking to integrate Bootstrap 5 toasts into my ASP.NET web application, I have the code below. HTML <div class="row"> <div class="toast" id="companyUpdOK" name="compa ...

Should I avoid declaring global app variables in Angular?

After browsing several examples online, I have come across a common pattern in AngularJS code. The basic structure involves creating a new module using the angular.module() method and then retrieving it in other files within the same module. var app = ang ...

What is the most effective method for combining data from two APIs into a single React table?

Looking to combine data from 2 separate APIs that both have pagination capabilities. What is the most efficient method to present the merged data in a table? The data needs to be joined based on their unique id, however one API provides fewer records tha ...

Connecting node.js to a MySQL database on a WAMP/XAMPP server: A step-by-step guide

As a PHP programmer, I am experienced with WP, CI, and OC. However, I am a complete beginner when it comes to node.js and how to connect MySql with WAMP/XAMPP in a step-by-step method. If I were to set up a live server for this project, what would be the ...

Navigation bar links not leading to the correct corresponding pages

Whenever I try to access index.php, it loads perfectly the first time, but I encounter an issue when trying to navigate to another page from the index page. Error: Object not found! The requested URL was not located on this server. The link on the ref ...

Is the jSON data featured at the top with DIV / Table Headers positioned at the bottom?

I'm really struggling with this issue. I've tried a few different things but nothing seems to work. Any suggestions on how to tackle this problem? Here's a link to a screenshot of the error I'm encountering... <div class="contain ...