Uncover hidden objects by utilizing the up and down arrow keys on a Ul element that has reached the edge of an overflow:auto container

My issue involves scrolling a ul up and down. The ul has overflow:auto applied, causing the selected item to be hidden after reaching a certain point. To see an example of the problem, visit this link: http://jsfiddle.net/NjC58/34/

The code I am currently using is mostly borrowed from this source:

var displayBoxIndex = -1;
var Navigate = function (diff) {
    displayBoxIndex += diff;
    var oBoxCollection = $("#leftDrop li");
    if (displayBoxIndex >= oBoxCollection.length) {
        displayBoxIndex = 0;
    }
    if (displayBoxIndex < 0) {
        displayBoxIndex = oBoxCollection.length - 1;
    }
    var cssClass = "selectedInitialNav";
    oBoxCollection.removeClass(cssClass).eq(displayBoxIndex).addClass(cssClass);
}

$(document).keydown(function(e){ // 38-up, 40-down
    if (e.keyCode == 40) { 
        Navigate(1);

        return false;
    }
    if (e.keyCode == 38) { 
        Navigate(-1);

        return false;
    }
});

I am seeking a solution that will automatically scroll the overflow to the top when pressing the down arrow key, reaching the bottom of the visible ul, and scroll the overflow down when pressing the up arrow key to ensure the selected li is at the bottom of the visible ul.

I have explored potential solutions using jQuery's scroll function, referencing this post, and this post (which discusses scrollTop), but have yet to find a suitable solution.

Answer №1

If you're looking for a way to handle scrolling using a custom function, one approach could be to create a function specifically designed for managing the scrollTop position of each item.

Custom Scroll Function

function customScroll(){
    if(window.event.keyCode == 40){
        document.getElementById("container").scrollTop = scrollPos;
        scrollPos = scrollPos + 19;  
    }           
    else if(window.event.keyCode == 38){            
        scrollPos = scrollPos - 19;  
        document.getElementById("container").scrollTop = scrollPos;
    }
}

After defining the function, make sure to call it within your Navigate function. Also, ensure that you assign an id to your ul element like this: <ul id="container">

Check out the JSFiddle Demo

This code may require further refinement, but it could be a useful starting point for your scrolling needs.

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

How can we use an Array containing nested Objects in TypeScript?

Wondering about the best way to achieve this: let x = [{}]; in TypeScript. I've searched high and low for a definitive answer to this query. My assumption is that it can be done using the Array object: let x : Array<Object> = new Array<Obj ...

The perplexing phenomena of Ajax jQuery errors

Hey there! I'm having a bit of trouble with ajax jquery and could use some guidance. $.ajax({ type:"get", url:"www.google.com", success: function(html) { alert("success"); }, error : function(request,status,error) { alert(st ...

Instructions for changing the background color continuously

One of my templates includes the following input: <div class="form-group" LayoutDirective=""> <label>Background color for views</label> <input type="text" name="background_color" id="background_color" ng-model="selectedLayout. ...

Using Laravel with Ajax can sometimes result in successful requests, while other times they may fail

I am facing some issues with my code as a junior programmer. Sometimes when I call data using Ajax in laravel 5.7, it is successful and the data is retrieved. However, upon refreshing, sometimes it is incomplete and logs show an error 500 in my PHP. Strang ...

Attempting to align text around an image within Bootstrap 4

I'm struggling to wrap text around my image at approximately 1355px. I attempted using float-left on both the div container and the img tag, but nothing seems to be working. Could it be due to the column setup I have in place? Should I perhaps add an ...

Alternating the tooltip icon based on the field's condition

Looking for a way to create a tooltip for an input field that involves changing icons based on certain conditions. An example scenario is the password field in a registration form. Seeking advice on the best approach to achieve this. Currently, here' ...

How can curly braces be utilized in an array reduce method?

If the function `fn3` is used instead of `fn2` in this code snippet running on node 9.5.0, the `console.log(totalUpvotes)` will display `undefined`. Shouldn't it actually be equal to 92? const posts = [{id: 1, upVotes: 2}, {id:2, upVotes: 89}, {id: ...

Determine whether to deliver compressed or uncompressed js and css files by utilizing url parameters in AngularJs and Grunt

Exploring the world of AngularJS and Grunt is a new adventure for me. I am currently in the process of setting up the front-end environment and am looking for a way to serve either compressed or uncompressed js and css files based on specific url parameter ...

Navigating advanced search through nuanced filters dynamically with AngularJS

Here you will find the advanced search form: https://i.stack.imgur.com/g7Hiz.png I have successfully created a URL and parameters for document sections, but I am struggling to come up with a solution for managing the "Add Property Restrictions" section w ...

Searching for automobiles using PHP and Ajax technology

During the development of my point of sale system, I encountered a problem with the search functionality. When entering the product code into the designated textbox, I intended for it to automatically search and display the product name and price in the co ...

Adjust grid column sizes automatically when a smaller number is declared - tailwind

I am working with the tailwind grid system and have specified 6 columns for each row. However, if the number of elements is less than 6, I would like it to resize them to 3. <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 grid-flow-r ...

Tips for triggering the button command event using JavaScript

Is there a way to activate the button command event using JavaScript? I'm not referring to the BUTTON onclick event. ...

What is the process for integrating a Browserify library module into a project as a standard file?

I have successfully developed a JavaScript library module with browserify --standalone, passing all tests using npm test. Now, I am working on creating a demo application that will utilize this library module in a browser setting. When I run npm update, th ...

Tips for making Ajax crawlable with jQuery

I want to create a crawlable AJAX feature using jQuery. I previously used jQuery Ajax on my website for searching, but nothing was indexed. Here is my new approach: <a href="www.example.com/page1" id="linkA">page 1</a> I display the results ...

Winning opportunities created by using credits in the slot machine

**Greetings, I have created a slot machine using JavaScript, but I am looking to enhance the player's chances based on their credits. Can anyone guide me on how to achieve this? Essentially, I want the player's odds to increase proportionally wit ...

ReactJS fetch request not receiving expected response from PHP script

When I make a fetch call from my componentDidMount() method, it returns undefined. The PHP file successfully returns JSON when accessed directly on a server, but the fetch call itself returns undefined. componentDidMount() { fetch("backend.php ...

Discover Vuejs: Display Less, Reveal More

In order to achieve a specific task, I need to display 12 items in 4 columns with 4 items each. Initially, only the first four items are visible and the rest are hidden until the user clicks the "Show More" button. Upon clicking the button, the next row ...

Could one achieve the task without the presence of a function?

When I execute the below code: let app = express() in the console, it outputs: { [EventEmitter: app] _events: { mount: [Function: onmount] }, _eventsCount: 1, _maxListeners: undefined, setMaxListeners: [Function: setMaxListeners], getMaxList ...

Finding the correct path for ts-loader with webpack version 2.2.1 within a script

When running the gulp task below, I encounter an error: Module not found: Error: Can't resolve 'app.ts' in 'wwwroot/js/admin' gulp.task("admin:js", function (done) { module.exports = { context: "wwwroot/js/admin", ...

Something is overriding the style created by makestyle material UI that I had implemented

How can I increase the importance of my makeStyles classes over default Material UI styles? Here is my code: import { createTheme, ThemeProvider } from '@mui/material/styles'; import { makeStyles, createStyles } from '@mui/styles'; co ...