The direction of the drop-down changes based on the available space

I'm new to programming and could really use your assistance.

I'm having a problem with the positioning of my drop down sub-menus. Specifically, I have a simple drop down in my header that is too close to the window border when certain permissions are applied.

As a result, the sub-menu opens beyond the window border on the right side, causing the content to be unseen by the user.

I'd like it to detect if there's enough space to open on the right side. If yes, then open on the right; if not, open on the left. Can you help me with this issue?

https://i.sstatic.net/moPKR.png

This is how it looks when there's enough space: https://i.sstatic.net/kr8Oj.png

Below is the HTML code:

<ul class="main-menu-list">
        <li class="header-dropdown-item">
            <span class="header-dropdown-item-title">Admin</span>
            <img src="../Layout/images//arrow-down.svg" alt="">
            <ul class="sub-menu-list">
                <li class="header-dropdown-item">
                    <a class="arrow-right header-dropdown-item-title">Users</a>
                    <ul class="sub-menu-list-right">
                        <li>
                            <a class="header-sub-menu-item">New
                                users</a>
                        </li>
                        ...
                        <li>
                            <a class="header-sub-menu-item" >3 Digit Code
                                Register</a>
                        </li>
                    </ul>
                </li>

... (HTML code continues)

And here's the CSS styling:

.sub-menu
    ... 

Finally, here's the Pure JS code snippet:

<script type="text/javascript">
    (function () {
        handleMenuItems();

        // functions:

        function handleMenuItems() {
            var menuEl = document.querySelector(".menu"),
                userLinksList = menuEl && menuEl.querySelector(".user-links"),
                recentlyItemListEl = menuEl && menuEl.querySelector(".recently-visited-item"),
                favoriteItemListEl = menuEl && menuEl.querySelector(".favorites-item");

            if (userLinksList) {
                ...
            }
        }

        ...

        })();
</script> 

Answer №1

It seems like finding a quick solution using CSS is not possible in this case. One approach could be to align the element to the left if there isn't enough space available. You can utilize the

document.querySelector("#sub-menu").getBoundingClientRect()
method to determine the position of the element.

{
    "x": 1261.5,
    "y": -309,
    "width": 298,
    "height": 452,
    "top": -309,
    "right": 1559.5,
    "bottom": 143,
    "left": 1261.5
}

After getting the position information, you can assess whether the sub-menu would overflow off the page and apply a specific class to make it align to the left rather than the right.

const subMenuBound = document.querySelector("#sub-menu").getBoundingClientRect();
const windowWidth = document.getElementsByTagName("body")[0].clientWidth;

const subMenuX = subMenuBound.x;
const subMenuWidth = subMenuBound.width;

if (subMenuBound.width + subMenuBound.x > windowWidth) {
    // Add a class to the sub-menu for left alignment
} else {
    // Remove the class
}

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

Is there a way in JQuery to apply the CSS of one element to another selected element?

I'm curious if there is a JQuery function available that can be used to transfer the exact CSS styles from one element to another. I want all the CSS properties to be applied without any additional inheritance. For example: <div id="d1"> &l ...

Using ng-disabled on input elements within an ng-repeat directive

Showing different inputs based on an array looks like this <div data-ng-repeat="n in langInput.values"> <input type="text" id="auction_name_{{n.selected}}" class="form-control" name="auction_name_{{$index}}" ...

Tips for wrapping text to fit the width of a column

Hello, I have a table with varying column widths as shown below ${"#goldBarList"} table tr td:first-child{width:5%;} ${"#goldBarList"} table tr td:first-child+td{width:5%;} ${"#goldBarList"} table tr td:first-child+td+td{width:6%;} ${"#goldBarList"} table ...

Populating a two-dimensional array with randomly generated numbers using javascript

Apologies if this has been asked before, but I couldn't find any previous posts on the topic as I'm still fairly new to this site! Lately, I've been exploring game development using HTML5 and JavaScript and have gotten into creating tileset ...

Why does the click event on a dynamically created checkbox in a jQuery datatable select the entire row instead of just the checkbox itself?

I have recently made an update to my jquery datatable where I included a new row with HTML content (a checkbox input) based on a specific event: $("#btn").on( 'click', function (){ $('#mytable').DataTable().row.add([data[0],data[1] ...

Make sure to include additional details, such as copyright information and a link to read more, when copying text. It is also important to maintain the

When attempting to include a read more link in my copied text, I am encountering an issue where the line breaks and formatting are being neglected: <script type='text/javascript'> function addLink() { var body_element = document.getEl ...

Are $(function() { }) and $(document).ready(function() { }) the same function under the hood?

Similar Question: What sets apart these jQuery ready functions? Do $(function(){}); and $(“document”).ready(function(){}); have the same meaning? Beginning javascript code with $(function, etc. This day, as I was examining some jav ...

Unlocking the Power of Combining JMVC and Server-side MVC Models

It's been a few days since I posted this question here and still no response. I also tried posting it on forum.javascriptMVC.com and finally got an answer, but I'm looking for more insights. Here's my question: After reading the documentat ...

Implementing nested popup windows using Bootstrap

I am facing an issue with my two-page sign-in and sign-up setup in the header of my angular2 project. On the sign-up page, I have a link that should redirect to the sign-in page when clicked, but I am struggling to make it work. Can someone provide guidanc ...

Enhancing middleware chaining in Express

Below is the code for my Express configuration: var server = express() .use(express.cookieParser()) .use(express.session({secret: buffer.toString('hex')})) .use(express.bodyParser()) .use(express.static('./../')); serv ...

What factors might cause varying WebGL extension availability?

When I analyze my code, I am checking for available WebGL extensions. console.log(GL.getSupportedExtensions()); This results in an array containing 9 extensions. https://i.sstatic.net/5sTcX.png However, upon inspecting my extensions on a platform like ...

Using the JSTL c tag within a JavaScript function

Is there a way to integrate jquery fullcalendar with MySQL using Spring MVC? I need to fetch schedule data from MySQL and display it on the calendar. Can you please demonstrate how to do this? <script type='text/javascript'> $( ...

When encountering [Error in render: "TypeError: Cannot read property 'length' of undefined"] across various files, what could be causing it to appear in more than one instance?

Currently, I am engrossed in a Vue tutorial centered around creating a basic email application. However, during my test run, the inbox's content failed to display as expected (referencing the images attached below). The first image depicts my version, ...

What is the method to designate the initial value of a <select> tag within a React component?

I am working with a basic <select> element that is looping through a set of options: <select onChange={(event) => this.setState({selectedOption: event.target.value }) }> { this.state.options.map(option => <option key={option.label} ...

Receiving an error when trying to import the 'marked' module into an Angular project

Working on a project with Angular 15, I recently added marked to transform MarkDown text to HTML using an Angular pipe. However, no matter how I import it, I can't seem to get it working and keep encountering errors. I followed these steps: npm i mar ...

Encountered an issue when trying to deploy NextJS application to AWS using the serverless framework

Encountered an issue while deploying my NextJS app to AWS using the serverless framework. After running npx serverless in my Next JS app directory, I received the following error: $ npx serverless error: Error: Command failed with ENOENT: node_module ...

I keep encountering an issue with a TypeError that says I am unable to read properties of undefined, specifically 'nativeElement'. Can anyone provide guidance on resolving this error

Here is the current state of my code: <mat-tree-node> ... <div *ngIf="node.type=='assembly' || node.type=='part'" style="display: inline;" (contextmenu)="asmStateServ.contextMenu($e ...

"Encountering a Reactjs error when trying to render a

Currently, I am engrossed in a React JS tutorial but seem to have hit a roadblock with the following error: Failed to compile. Error in ./src/Components/Projects.js Syntax error: Unexpected token (15:10) return { <ProjectItem key={projec ...

What manner must I understand this syntax?

After stumbling upon this code snippet online, I was left scratching my head: function cjsDetectionPlugin() { return { name: 'cjs-detection', moduleParsed({ id, meta: { commonjs: { isCommonJS } } }) { ...

Fixed positioning of a div causes it to move further away when zooming out

Greetings to all! I am looking to achieve a scrolling effect for a div area as I scroll down the page. To accomplish this, I have utilized the CSS property position:fixed to lock the div area within another div called "page". Below is the corresponding CSS ...