Determine whether there is greater available space above or below a specific element within the DOM

I'm looking to create a dynamic layout where an input field is accompanied by a list in a div, positioned either above or below depending on available space. This setup needs to account for the fact that the input field could be located anywhere on the page. I am considering using viewport dimensions to determine the placement of the div and input field. I would like to achieve this effect using CSS and HTML exclusively. Any suggestions or recommendations on how to tackle this challenge are welcome.

Here is my basic HTML structure:

<input/>
<div id="container">
   <ul>
      <li ngFor> 
        <span> field1 </span>
        <span> field2 </span>
        <span> field3 </span>
      </li>
   </ul> 
</div>  

Answer №1

To provide a comprehensive answer, it is necessary to understand the structure of your components. However, there are some HTML features that could be useful depending on whether you need to make decisions based on space within the viewport or the parent component.

If you prefer making decisions based on space within the viewport, you can utilize Element.getBoundingClientRect() to determine the distance between the input and the top/bottom of the viewport:

const element = document.querySelector('input');

const elementRect = element.getBoundingClientRect();

const spaceAbove = elementRect.top;
const spaceBelow = window.innerHeight - elementRect.bottom;

if (spaceBelow < spaceAbove) {
  // code to render with more space above input
} else {
  // code to render with more (or equal) space below
}
<input />

If you want to base your decision on space within the parent component, you can use Element.offsetTop and Element.offsetHeight to calculate the space between the input and the top/bottom of its closest positioned ancestor:

const element = document.querySelector('input');

const spaceAbove = element.offsetTop
const spaceBelow = element.parentNode.offsetHeight - (element.offsetTop + element.offsetHeight)

if (spaceAbove > spaceBelow) {
  // take action
} else {
  // take another action
}
<div style="padding: 200px 0 100px 0; position:relative">
<input />
</div>

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

Discover the process of incorporating secondary links into your dabeng organizational chart!

I need to incorporate dotted lines on this chart, such as connecting leaf level nodes with middle level nodes. import OrgChart from '../js/orgchart.min.js'; document.addEventListener('DOMContentLoaded', function () { Mock.mock(&apo ...

Begin 5 seconds after loading

First time attempting this task. My goal is to trigger the loading of an I have been trying to write a script for this, but it's not functioning as expected. HTML : <div id="div1"> <a id="single" href="#">Single Play</a> & ...

Methods to Retrieve Data in Directive

Below is the directive I am working with: directive('checkKey', function() { return { restrict: 'A', scope: { min: '=' }, link: function(scope, elem, att ...

Is there a way to detect if JavaScript is disabled using a unique CSS selector?

Does anyone know of a CSS selector that can be used when JavaScript is disabled? I'm not referring to the noscript tag, but specifically in CSS. ...

Is there a way to modify sections of an href link depending on the URL selector?

<a class="change_this" href="http://www.site1.com">Link 1 Type 1</a> <a class="change_this" href="http://MyID.site1.com">Link 1 Type 2</a> <a class="change_this" href="http://www.site2.com/?refid=myid2">Link 2 Type 1</a> ...

Load information from a JavaScript object when the user clicks dynamically

My challenge involves utilizing a JavaScript object that contains video information such as title and source URL. Within my HTML, I have image placeholders and the goal is to trigger a modal pop-up (using Twitter Bootstrap modal) of the specific video when ...

Variations in key options based on specific situations

Is it possible to make certain keys required in Typescript depending on the circumstances? For instance interface IDog { name: string; weight: number; } class Retriever implements IDog { name = "Dug"; weight = 70; public updateAttribute(props ...

The default setting for the calendar picker indicator should be enabled

Whenever I hover my mouse over it, an indicator pops up, but I want to make it the default <input type="date" class="form-control" name="Date" [(ngModel)]="opening_date" (ngModelChange)="Operating()" style="width:550px" required> inp ...

What is the method for assigning a string to module variable definitions?

As someone new to TypeScript and MVC, I find myself unsure if I am even asking the right questions. I have multiple TypeScript files with identical functionality that are used across various search screens. My goal is to consolidate these into a single fil ...

What are the steps for implementing CSS in Markdown?

How can I incorporate a CSS class into a Markdown file? For example, using <i class="icon-renren"></i> (from the fontawesome library) should display an icon when its CSS file is imported in HTML. Is there a way to achieve this in Markdown? ...

Guide on setting up @types from an NPM module containing the "@" symbol in its title

Installing the node package is easy npm install @gamestdio/timer --save But when attempting to add the corresponding types npm install @types/@gamestdio/timer --save An error occurs Invalid package name "@types/": name can only include URL-friendly ch ...

What is the method for creating a HTML test report using Python incorporated into my code?

from selenium import webdriver import unittest, time, re import HTMLTestRunner class TestAutomation(unittest.TestCase): def setUp(self): self.errors = [] self.driver = webdriver.Chrome() self.driver.get("http: ...

"What is the best way to include additional fields within a popover in an AngularJS application

This is my code for implementing a popover using AngularJS. I am trying to figure out how to add custom styling to the popover HTML, but I am having trouble binding elements in that part of the code. <!DOCTYPE html> <html> <head> <l ...

Can you tell me the name of the scrolling effect used for the background on this website?

Hello everyone, I have a question to ask. Be gentle with me as this is my first time posting here. I've been learning CSS3 and recently came across an effect that caught my eye. I'm not sure if it falls under the category of parallax scrolling or ...

Generate HTML output from the container element of a Vue application

On my HTML page, I have integrated a Vue application that consists of a single component. This application is attached to an element with the id paid-content. index.html <div id="paid-content"> <h2>You should see this if you' ...

Unraveling the mysteries of webpack configuration

import * as webpack from 'webpack'; ... transforms.webpackConfiguration = (config: webpack.Configuration) => { patchWebpackConfig(config, options); While reviewing code within an Angular project, I came across the snippet above. One part ...

Trouble Updating Selected Element in Android 2.3.x

Our team is currently working on a Web application that uses JavaScript to dynamically create elements. While testing for mobile usability, we have encountered an issue with select element behavior on Android devices running 2.3.x versions. When a user tou ...

Passing extra arguments to a callback function in Typescript

I'm trying to pass a parameter to a callback function. Below is the snippet of my function: let func = function(el, index){ if(el.id === myId) return index; } arr = [obj1, obj2, obj4, ...]; arr.filter(func); Is there a way to suc ...

Angular 2 routing for dynamic population in a grid system

My website is compiling correctly, however, in the Sprint dropdown menu where I have set up routing... <a *ngFor = "let item of sprint;" routerLink = "/Summary" routerLinkActive = "active"> <button *ngIf = "item.Name" mat-menu-item sty ...

What is the best way to vertically align a Material UI component to occupy the remaining space within a container

Issue with Material UI/Grids for Login Page As a newcomer to Material UI/Grids, I am currently working on creating a login page where the layout is split into two parts. The left side occupies 5 column spaces while the right side takes up 7 column spaces. ...