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

Pass data from viewmodel back to controller in C# MVC

One of the challenges I am facing is in a view that allows users to add items to a table. Using a simple HTML form and jQuery, new rows are dynamically added to the table. I am seeking a way to efficiently pass the added rows from the view to the controll ...

Attempting to output numerical values using Jquery, however instead of integer values, I am met with [Object object]

I am struggling to figure out how to display the value contained in my object after attempting to create a Calendar using Jquery. I attempted to use JSON.toString() on my table data, but it didn't solve the issue. Perhaps I am not placing the toString ...

Challenges with NPM testing

Are there any reported issues with npm on Ubuntu 18.04? Or are there known solutions to the 100:1 error? I am currently enrolled in a course and it's crucial for me to be able to execute code using npm test. Despite multiple attempts at deleting and ...

Adding ngrx action class to reducer registration

Looking to transition my ngrx actions from createAction to a class-based approach, but encountering an error in the declaration of the action within the associated reducer: export enum ActionTypes { LOAD_PRODUCTS_FROM_API = '[Products] Load Products ...

Monitor modifications to an <input type="text"> element as its value is updated dynamically through JQuery from the server side

I am struggling with detecting when the value of an input field changes after it has been set by clicking a button. I have tried various events but can't seem to find the right one. <!DOCTYPE html> <html> <head> <script src=" ...

Looking to verify characters, numbers, and special characters with jQuery's regular expression feature?

Currently, I am facing a challenge in validating the password field to allow characters, numbers, and special characters. It is essential that the password consists of exactly 8 characters. Despite searching online for a solution, I have been unsuccessful ...

Ways to distinguish between two div elements that have scroll bars and those that do not

I created a div with CSS styling. .comment-list { margin: 20px 0; max-height: 100px; min-height: 100px; overflow-y: scroll; width: 100%; background-color:#000; } Here is the HTML code for the div: <div class="comment-list"> </div> When the ...

PHP-generated interactive pie chart

I'm encountering a puzzling issue while attempting to create a pie chart in Flot using data from PHP. The chart seems to be rendering incorrectly, and I'm struggling to identify the cause. Below is my PHP code (used for testing): echo json_enc ...

"Enhance Your Website with Stylish Bootstrap Pop

Hello, I am trying to display a "Loading..." text or spinner image while waiting for the dynamic ajax content to load. Due to the large amount of data that needs to be fetched, it takes approximately 2-3 seconds for the content to fully load. Below is my ...

Dynamically loading an iFrame source and automatically populating input forms using Javascript explained

My current challenge involves retrieving URL parameters successfully and using them to decide which iframe src to populate. Additionally, I need to autofill the form created via the form src with other parameters. However, I am faced with two main issues. ...

Having trouble retrieving the necessary data to generate a menu, the getStaticProps function is coming back as undefined

I'm currently working with Next.js 13 & Strapi, and my goal is to create a Menu component utilizing the getStaticProps function. To achieve this, I've implemented a Layout component within the _app.js file, and nested a Menu component inside the ...

Generate a new item using an existing one

I am seeking to extract the desired output from the provided input: Input Configuration: var inputParams = { 'inputDetails' :[ { 'field' : 'specificationName', 'value' : 'strong'}, { ...

The fuse-sidebar elements are not being properly highlighted by Introjs

I have recently developed an angular project that utilizes the fuse-sidebar component. Additionally, I am incorporating introjs into the project. While introjs is functioning properly, it does not highlight elements contained within the fuse-sidebar. The ...

retrieve PHP function calls as an array using Ajax

While working in PHP, I have encountered a situation where I needed to call a PHP function using AJAX: <button onclick="loop()">Do It</button> function loop() { $.get("ajax.php", { action: "true" }, function(result) { $("in ...

The code is slicing data, but the changes are not reflecting in the user interface

Initially, there are three drop down menus displayed. Upon selecting an option from the first drop down menu, the values in the second drop down menu load. After selecting an option from the second drop down menu, a new set of drop downs appears. However, ...

Encountering a problem with the Ionic Modal Slider: unable to locate the matching element associated with delegate-handle= when using $

I am encountering a problem with my Ionic application that features multiple Angular controllers. Specifically, I have a LoginCtrl and RegisterCtrl controller set up. The issue arises when I try to trigger a modal with a slider from the RegisterCtrl by usi ...

"Convert a jQuery array into a JSON format compatible with PHP

Using jQuery, I am extracting various text nodes (p) and headers from a source and storing them into arrays: var textnode = $(source).children("p:not(:has(img))").map(function () { return $(this).outerHTML(); }).get(); var headerone = $(source).child ...

Postpone the inclusion of html files within ng-include in AngularJS

I need to optimize the startup performance of my app by delaying the loading of a series of HTML files that are being included into my main controller. These files are not needed for at least 4 seconds while one specific HTML file processes. How can I de ...

Using a combination of Ajax and jQuery in Rails4 to showcase a date in the %m/%d/%yyyy format ultimately results in a split

Recently, I encountered an issue with an ajax call that retrieves a date from the database. The date is stored as a double in the database and then converted to a string. I used Date.parse to change it into a date object and used strftime to format it. How ...

The require() function is not functioning properly, even after I tried switching the type from module to common. As a newcomer to this, there may be something essential that I

Despite changing the type from module to common, I am still unable to get require() to work. As a newcomer to this, there may be something I'm overlooking that I can't quite pinpoint. I attempted const express = require('express'); but ...