I need to implement a div-based dropdown with a scrollbar in JavaScript and CSS to prevent it from extending beyond the screen. Additionally, the use of struts is essential in this implementation

Dealing with a dynamically populated div-based dropdown can be tricky, especially when it extends beyond the screen's limits and hides entries. This is an inherited application that lacks support, leaving me to handle it without the necessary expertise. I could really use some simple explanations here. Apologies for the information overload.

After scouring through Google and dissecting other parts of the code, I believe using an optionsCollection could resolve this specific issue. However, I am stuck on how to trigger a function to update other data when the selected value changes while using optionsCollection.

The complexity of the problem makes it impossible to share in its entirety. Therefore, I'll attempt to provide the relevant code snippets.

Here's where the trouble begins:

<div class="empform">
<html:form action="/processBlank">
<div id="divJobClass" style="visibility: hidden; position: absolute; height="50px"
 border-color: #fff; border-style:solid; border-width: 1px; background: white; opacity: 1">
    <table id="tableJobClass" cellspacing="0" style="border-color: #9090ff; border-style:solid; border-width:1px;" cellpadding="0"> <%
ctr = 0;
for (JobClassVO jc : jcList) { // href="setJC(<%=jc.getGuid()% >, '< %=jc.getJcIdDesc()% >')"  %>
    <tr><td><input style="border: none; background: white"  type="text" 
        id="jc<%=ctr%>" size="50" value="<%=jc.getJcIdDesc()%>" readonly="readonly"
        onclick="setJC(<%=jc.getGuid()%>, '<%=jc.getJcIdDesc()%>', <%=ctr%>)"
        onkeydown='jcListCheck(event);'></td></tr><%
ctr++;
}
%>

This snippet demonstrates how the drop-down activates upon field click:

<td>
        <html:hidden name="erfEmployee" property="jcGUIDString" indexed="true"/>
        <html:text name="erfEmployee" property="jcId" indexed="true"
            size="8" maxlength="25" onblur='<%= "isLastRow('JobClass', " + count + ");" %>'
            onclick='<%= "showJcList(" + count + ");" %>' 
            onkeydown='<%= "jcCheck(event," + count + ");" %>'
            onchange='<%= "verifyHoursClass(" + count + ");" %>' readonly="true" />
</td>

Functions like isLastRow, jcCheck, and onChange do not affect the appearance.

These functions are responsible for displaying the div:

function showJcList(index) {
    var fld = elem("erfEmployee[" + index + "].erfEeSsnFormatted");
    if (fld.value == "")
        return;
    var div = elem_("divJobClass");
    jcGuidTarget = elem("erfEmployee["+index+"].jcGUIDString");
    jcIdTarget = elem("erfEmployee["+index+"].jcId");
    showList(jcIdTarget, div, jcGuidTarget);
    focusSelected("jc", null, <%=jcList.size()-1%>);
}

function showList(idTarget, div, guidTarget) {
    ddDiv = div;
    if (ddDiv.style.visibility == "visible") {
        ddDiv.style.visibility = "hidden";
        return;
    }
    var iTop = 0, oNode = idTarget, iLeft = 0;
    while(oNode.tagName != "BODY" && oNode.tagName != "HTML") {
        iTop += oNode.offsetTop;
        oNode = oNode.offsetParent;
    }
    oNode = idTarget;
    while(oNode.tagName != "BODY" && oNode.tagName != "HTML") {
        iLeft += oNode.offsetLeft;
        oNode = oNode.offsetParent;
    }
    ddDiv.style.left = "" + iLeft + "px";
    ddDiv.style.top = "" + (iTop + idTarget.offsetHeight) + "px";
    ddDiv.style.visibility = "visible";
    ddIdTarget = idTarget;
    ddGuidTarget = guidTarget;
}

Multiple online resources suggested using overflow:auto and setting a fixed size to tackle this issue, but this hasn't produced any visible changes. Perhaps my sizing arrangement was off. Though overflow:scroll added scroll bars, they only extended along with the overflowing div, exceeding the screen. I even debated calculating available space to adjust the div height accordingly, but that solution seems inelegant. Nevertheless, I'm open to suggestions, advice, or any innovative ideas. Thanks!

Answer №1

This is a common issue that arises when designing expanding widgets.

To resolve this, follow these steps:

  1. Specify a desired max-height for the element;
  2. Add overflow-y: auto to allow scrollbars only when necessary;
  3. Use JavaScript to calculate whether the sum of the element's top position and height exceeds the viewport's height (the visible area of the window);
  4. If overflow occurs, adjust the dropdown behavior by reversing its direction to start from the bottom of the parent element and expand upwards.

Please refer to the jsFiddle example created using jQuery for a visual demonstration. Resize the window to observe how the overflowing element behaves.

You can also execute the code snippet below:

$(".dropdown li").on('mouseenter mouseleave', function(e) {
  var submenu = $('ul:first', this);
  var submenuTop = submenu.offset().top;
  var submenuHeight = submenu.height();
  var viewportHeight = $(window).height();

  var isOverflowing = (submenuTop + submenuHeight > viewportHeight);

  if (isOverflowing) {
    submenu.css("top", $(this).height() - submenuHeight);
  } else {
    submenu.css("top", 0);
  }
});
* {
  box-sizing: border-box;
}

body {
  background: dodgerBlue;
}

.dropdown,
.dropdown li,
.dropdown ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

/* Additional CSS styling properties */

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<ul class="dropdown">
  /* Dropdown content structure */

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

Storing a table structure in a variable using JavaScript

Kindly review this arrangement: 1 | 2 | 3 | .... ---------------------------------------------------------- 2016 100 2000 500 2015 540 450 1200 2014 120 230 660 I am seeking a method ...

The Colorful World of CSS Backgrounds

I've been searching for hours trying to track down the source of this strange greenish background color. I've combed through every single file and it's starting to drive me insane. Any ideas where this color could be coming from? I highly d ...

Unexpected behavior from vuelidate triggered on blur

I have implemented vuelidate for form validation. My goal is to validate user input either when they move to the next input field or click outside of the current one. <div class="form-group col-md-6" :class="{invalid: $v.partner.email.$ ...

Error: Attempting to access the 'url' property of an undefined variable, despite specifically checking for its undefined status

Within my React application, I am utilizing the following state: const [functions, setFunctions] = useState([{}]); I have created a test to check if a specific property is undefined: if (typeof functions[functionCount].url !== "undefined") { ...

Experiencing discrepancies in pixel height while conducting tests using Nightwatch

Let me start by sharing some details about my machine setup: Operating System: CentOS 7 Graphics Drivers: kmod-nvidia (dedicated GPU) I am currently testing a webpage using Nightwatch, and one of the requirements is to ensure that a background image&apo ...

utilize images stored locally instead of fetching them from a URL path in a Vue.js project

Hey there fellow Developers who are working on Vuejs! I'm encountering something strange in the app I'm building. I am attempting to modify the path of image requests based on a particular result, which causes the images to change according to th ...

Using HTML5 Canvas to draw intersecting polygons

Recently, I came across a polygon drawing function that caught my attention: Polygon.prototype.draw = function(ctx) { ctx.save(); ctx.beginPath(); var v = this.vertices[0] ctx.moveTo(this.position.x + v.x, this.position.y + v.y); var i ...

the typeahead.js method in Twitter's process() function is filling the list with undefined values

I am encountering a similar issue as described in the thread Twitter Typeahead Ajax results undefined. Since that problem remains unresolved, I am revisiting the topic with hopes of shedding light on any missing details. My setup includes standalone Typea ...

NodeJS experiencing a hitch in the image upload process

I am currently working on a Node code snippet that is used for uploading images. The images I am dealing with have sizes ranging from 10 to 200K, so they are relatively small in size. However, the issue I am facing is that Node seems to get stuck process ...

What is the best way to ensure that a sidebar occupies the entire height of our webpage?

Here is the current layout of my sidebar: I want it to always occupy full height, how can I achieve this? I've tried using height: 100%, but it doesn't seem to work. Here is my CSS code: #sidebar { /* Make sure to include all previously men ...

Creating resizable rows of DIVs using jQuery

I'm currently developing a scheduling widget concept. The main idea is to create a row of DIVs for each day of the week. Every row consists of a set number of time periods represented by DIVs. My goal is to enable the resizing of each DIV by dragging ...

Discovering the summation of chosen options multiplied by input fields with the assistance of jQuery

I am attempting to calculate the average for different subjects and print it immediately whenever the user modifies a value. To input the marks, I am using input fields and corresponding select options for the hours allotted to each subject. I can accura ...

Which is Better for Creating DropDown Menus: CSS or JavaScript?

Starting a new project that involves dropdown menus with categories and subcategories within them. I'm curious about the advantages of using CSS3 only menus compared to traditional JavaScript ones. There are several jQuery menu options available as we ...

Update the regular expression pattern to extract nested tags and store them in an array of objects

For my small application, I am working on creating a regex pattern to identify "faux" html tags. The goal is to capture these tags within curly brackets and output them into an array of objects. Below is the code snippet with the current regex pattern: { ...

Building a custom HTML and JavaScript player to showcase multiple videos on a webpage

UPDATE: The solution has been discovered, shared, and marked as the top answer below. In the process of creating my portfolio website using HTML, CSS, and JS, I encountered a challenge regarding the addition of multiple videos on various pages. While fol ...

Angular 2 - Error: Regular expression missing forward slash syntax

Recently, I began working on an Angular 2 tutorial app using this repository. While I can successfully launch the app and display static content, I am facing challenges with rendering dynamic content from the component. I have a feeling that the error migh ...

My goal is to monitor every action (button) that users take while using the PDF viewer

Each browser displays the view differently, and I am interested in monitoring specific user actions such as button presses on a PDF viewer. I am currently setting up an iframe and configuring its attributes. Is there a way to achieve this? ...

JavaScript string manipulation function

Hey everyone, I need help finding a one-line solution in JavaScript to determine if a string contains a semicolon without using a loop. If anyone knows how to do this, please share your knowledge! ...

Deactivate hover effects and media queries for Material UI controls in all states

Since I am using a touch-capable monitor, I noticed that hover styles are not showing up on any controls. Specifically, when I hover over a Material UI button, I see the following styles: https://i.stack.imgur.com/uwBpt.png Is there a way to disable all ...

What is the process for transferring a file's contents to my server?

I am currently working on allowing users to import an OPML file that I parse server-side in my Rails application. However, I am facing difficulties as it appears that my server is not receiving the information correctly (neither the success nor error funct ...