Positioning of Bootstrap menu subnavs on the left or right is adjusted based on the

In my project utilizing Bootstrap and jQuery, I have implemented a multi-level menu. While everything functions correctly, there is one issue - when a menu item is placed too far to the right, its sub-menus extend beyond the page and become unreadable (as shown in the screenshot captured from jsFiddle):

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

I am seeking a solution to detect if a submenu extends beyond the page limit when it is opened. If this occurs, is there a way for the submenu to be positioned on the opposite side of its parent element?

Presently, my code looks like this:

HTML:

<nav class="navbar navbar-default navbar-fixed-top">
    <div class="container">
        <!-- Brand and toggle get grouped for better mobile display -->
       <!-- Code snippets shortened for brevity -->
</nav>

CSS:

.dropdown-menu>li>a:hover{
    background-color:rgba(216,216,216,1);
   <!-- Additional CSS styles listed in the original text are omitted here  -->
}

JS:

$(document).ready(function(){
  $('a[data-toggle=dropdown]').on('click', function(e){
    //$(this).next('ul').show();

    //console.log('click');
    e.stopPropagation();
    e.preventDefault();
    $(this).parent().siblings().removeClass('open');
    $(this).parent().toggleClass('open');
  });
  if($('.dropdown-menu').hasClass('open')){
    console.log('visible');
  }
});

For further exploration and testing, you can access the fiddle here: https://jsfiddle.net/311mcf23/

Any assistance or insights on resolving this issue would be greatly appreciated.

Answer №1

While conducting my investigations, I stumbled upon this interesting topic: How to determine if an element is out of view

Following the recommendation from @Sam Sehnert, I decided to utilize a plugin available at this location: https://github.com/customd/jquery-visible

With some adaptations, I achieved the precise outcome I was seeking!

Here is the HTML code snippet:

<nav class="navbar navbar-default navbar-fixed-top">
    <div class="container">
        <!-- Brand and toggle for improved mobile display -->
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">LOGO HERE!</a>
        </div>

        <!-- Navigation links setup -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav navbar-right">
                <li><a href="/">Home</a></li>
                <li><a href="#">About Us</a></li>
                <li><a href="#">Services</a></li>
                <!-- More navigation items here -->
            </ul>
        </div><!-- /.navbar-collapse -->
    </div><!-- /.container -->

Here's the CSS code fragment:

.dropdown-menu>li>a:hover{
    background-color:rgba(216,216,216,1);
    background-image:none;
    color:#000;
}
.divider{
    background-color:#fff;
}
<!-- More CSS styles included -->

Lastly, the JavaScript (JS) component:

(function ($) {
// JS function logic goes here
})(jQuery);

$(document).ready(function () {
    // Event handling and functionality implementation in this section
});

You can view the complete result on this demonstration page: https://jsfiddle.net/captain_theo/311mcf23/2/

I trust that this solution will be beneficial to others encountering similar challenges.

Sincerely, Theo

Answer №2

consider removing the following code snippet from the CSS file

.dropdown-submenu>.dropdown-menu{
top:0;
left:100%;
margin-top:-6px;
margin-left:-1px;
-webkit-border-radius:0 6px 6px 6px;
-moz-border-radius:0 6px 6px 6px;
border-radius:0 6px 6px 6px;}

Answer №3

Detecting collisions with the viewport may present some challenges. One possible solution could be to adjust the positioning of submenus by moving them to the left, as shown in the code snippet below:

.dropdown-submenu>.dropdown-menu{top:0;left:-99%;max-width:180px;margin-top:-6px;margin-right:-1px;-webkit-border-radius:6px 6px 6px 6px;-moz-border-radius:6px 6px 6px 6px;border-radius:6px 6px 6px 6px;}
.dropdown-submenu:hover>.dropdown-menu{display:block;}
.dropdown-submenu>a:after{display:block;content:" ";float:left;width:0;height:0;border-color:transparent;border-style:solid;border-width:5px 5px 5px 0;border-right-color:#999;margin-top:5px;margin-right:10px;}
.dropdown-submenu.pull-left>.dropdown-menu{left:-100%;margin-left:0px;-webkit-border-radius:6px 6px 6px 6px;-moz-border-radius:6px 6px 6px 6px;border-radius:6px 6px 6px 6px;}
.dropdown-menu-right {margin-left:0;}

Visit this link for more information and examples.

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

What steps can be taken to ensure that the on-click feature does not require continuous mouse holding to remain active?

I'm working on getting my search boxes to change color when clicked, but currently it only changes color while I am holding down the mouse button. Once I release the cursor, it reverts back to its original color. How can I make it so that it changes c ...

Adding the "input-invalid" class to the input doesn't take effect until I click outside of the input field

When the zipcode field is updated, an ajax call is made. If there are no zipcodes available, I want to mark it as invalid by adding the "input-invalid" class. However, the red border validation only appears when clicking outside of the input field. Is ther ...

PreventDefault doesn't work well with Bootstrap toggling data

When working with a list of elements, each containing an ng-click, I encountered an issue. Nested inside each element is a div that is meant to toggle a Bootstrap modal. To prevent the ng-click event from the parent element from firing, I added $event.sto ...

The IIS URL rewrite is causing issues with the rewriting of CSS and JS files

Struggling with my URL rewrites - every time I set up a rewrite for a page, it ends up affecting the CSS and JS files linked within the webpage, resulting in them not displaying properly. In an attempt to fix this issue, I tried using fully qualified path ...

Connecting a CodeIgniter controller method from jQuery code in a view file located in a folder: A step-by-step guide

I have implemented the autocomplete plugin in jQuery like this: $(function(){ $("#username").autocomplete({ source: "http://localhost/websitename/index.php/admin/suggest_names" // path to the method in controller }); }); This is ...

The dropdown menu does not automatically align with its parent element's position

<div className="inner-dark-section"> <div className="search-section" style={{ width: "100%", position: "sticky", top: "0", ...

Opacity of absolutely positioned elements

I am currently working on creating a popup box that will gray out the surrounding area. The problem I'm facing is that the opacity of the shadow div seems to be overriding that of the popup. I have tried changing the position from absolute to fixed an ...

What could be causing the repetition of the same cookie in my request header when using jQuery ajax?

Stuck in a dilemma for hours now, seeking assistance or suggestions from anyone who can help me out. To sum it up, I have an asp.net web api application where I am trying to fetch data from a web api and populate multiple dropdown lists on a page using jQ ...

Looking to incorporate multiple accordion drop down menus on your website? Utilize a combination of HTML, CSS, and JavaScript to

I am experiencing a challenge with implementing multiple accordion menus on my website. Whenever I attempt to duplicate the code, the new accordion menu appears but clicking on the first bar simply scrolls me back to the top of the webpage. Below is the H ...

We encountered a ReferenceError while trying to concatenate strings in JavaScript, indicating that en_EN is not properly defined

In my JavaScript code, I am attempting to combine strings together using the following syntax: var locale = {{ app.request.locale }}_{{ app.request.locale | upper }} + '.json'; The variable {{ app.request.locale }} can be either en, es, fr, or ...

What is the best way to customize the appearance of the initial row in each tr cluster?

Looking to add a button for expanding child rows within a datatable, with each group in the table having the same child elements.... The provided CSS currently displays the icon on every row throughout the entire table. td.details-control { backg ...

Using CSS to create hover effects for specific classes of elements

Is there a way to make the button change color on hover when hovering over anywhere in the navigation bar (.topNav) instead of just when hovering over the individual button elements (.top, .middle, .bottom classes)? I tried using span to achieve this, but ...

Exploring the process of logging in and managing PHP sessions in a jQuery mobile application

Creating sessions for a mobile application using JQuery has proven to be a challenge for me. The main goal is to have the application check if a user session exists, and if not, redirect them to a login form. Through ajax, the login credentials are authent ...

Invoking jQuery methods upon the loading of the page

b.delegate(".uipro_open_left", "click", function(){$.uiPro.open("left")}); b.delegate(".uipro_open_right", "click", function(){$.uiPro.open("right")}); Is there a way to automatically trigger these functions on page load? I appreciate any assistance you ...

Dynamically linking tabbable tabs is a useful technique that allows for

I have been working on an app that organizes websites into groups displayed as tabs in a tabbable navigator using Twitter Bootstrap. The idea is that each time a new group is added, a new tab should appear. Currently, this is how it looks: The functionali ...

Why isn't $.post functioning properly in any instance?

I've been experiencing issues with my $.post calls throughout my code. Despite not sending requests to different domains, everything is localhosted. My Mac OS X 10.8 automatically defined my localhost alias as ramon.local, and I'm trying to make ...

A method for conditionally looping to match header rows with data rows in a map

When dealing with two types of rows: header rows and data rows, each consisting of 18 columns. The number of data rows is determined by the number of header rows, for example: If there are 2 header rows, there should be (2 data rows: first one maps to th ...

The functionality of the tree grid bootstrap is not functioning properly when it is dynamically generated, but it works seamlessly when implemented statically

The code below functions correctly and provides the expected output. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="TreeView_Table_Project.WebForm1" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/ ...

Require assistance in understanding JSON data in the form of a variable

Apologies for any language barriers, but I have encountered a problem that I need help with. I am trying to create a highchart from an AJAX call. The following code works perfectly: chartOptions = { chart: { renderTo: 'grafica1', type: 'ar ...

"I am experiencing a problem where the CSS code is not reflecting on my Flask application

I am currently trying to learn how to develop flask applications. However, I've encountered an issue where the CSS code I write never seems to be applied when linked to my HTML template. No matter what I try, the styles just won't show up. Here ...