The dropdown menu is extending outside the header in a right-to-left (RTL) direction

I have implemented the jQuery code below to prevent the dropdown from extending beyond the header area. It works perfectly in the normal LTR version.

However, I need a solution for the RTL version. How can I achieve this?

jQuery

$('.primary-menu .dropdown-menu').each(function() {
        var menu = $('#header .header-row').offset();
        var dropdown = $(this).parent().offset();

        var i = (dropdown.left + $(this).outerWidth()) - (menu.left + $('#header .header-row').outerWidth());

        if (i > 0) {
            $(this).css('margin-left', '-' + (i) + 'px');
        }
    });

HTML

<header id="header">
<div class="container">
  <div class="header-row">
    <div class="header-column justify-content-start"> 
      
      <div class="logo me-3"> ..... </div>
      
      <!-- Primary Navigation
      ============================== -->
      <nav class="primary-menu navbar navbar-expand-lg">
        <div id="header-nav" class="collapse navbar-collapse">
          <ul class="navbar-nav me-auto">
            <li><a href="#">Link</a></li>
            <li><a href="#">Link 2</a></li>
            <li class="dropdown dropdown-mega"> <a class="dropdown-toggle" href="#">Pages</a>
              <ul class="dropdown-menu">
                <li>
                  <div class="dropdown-mega-content">
                    ........
                  </div>
                </li>
              </ul>
            </li>
          </ul>
        </div>
      </nav>
      <!-- Primary Navigation end --> 
    </div>
  </div>
</div>

I attempted the following, but it didn't work

$('.primary-menu .dropdown-menu').each(function() {
        var menu = $('#header .header-row').offset();
        var dropdown = $(this).parent().offset();

        var i = (dropdown.right + $(this).outerWidth()) - (menu.right + $('#header .header-row').outerWidth());

        if (i > 0) {
            $(this).css('margin-right', '-' + (i) + 'px');
        }
    });

Answer №1

The correct calculation for the offset is:

(window's width) - (element's left offset + element's outer width)

After careful consideration, I have arrived at the following final solution:

$('.primary-menu .dropdown-menu').each(function() {
    var menuOffset = $('#header .header-row').offset();
    var dropdownOffset = $(this).parent().offset();
    
    var rightMenu = ($(window).width() - (menuOffset.left + $('#header .header-row').outerWidth()));
    var rightDropdown = ($(window).width() - (dropdownOffset.left + $(this).parent().outerWidth()));
        
    var offsetDifference = (rightDropdown + $(this).outerWidth()) - (rightMenu + $('#header .header-row').outerWidth());

    if (offsetDifference > 0) {
        $(this).css('margin-right', '-' + (offsetDifference) + 'px');
    }
});

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

Update the div on the current page using externally retrieved information

Once again, I find myself stuck on a problem. Allow me to explain. Within this div, I have retrieved data using HTML SIMPLE DOM from another site. Like so: <div id="data">.....</div> Currently, the data refreshes whenever the user reloads th ...

Scroll positioning determines the height of an entity

Here's a code snippet I'm working with: HTML: <div id="wrap"> <div id="column"></div> </div> CSS: #wrap { display: block; height: 2000px; width: 400px } #column { display: block; height: 20px; ...

Lazy Highcharts and Foundation clash when loading JavaScript

I'm currently utilizing lazy_high_charts along with foundation 4. Within my view, I have included <%= high_chart("my_id", @chart) %>, which produces the following: <section> <script type="text/javascript"> (function() { ...

Why does JavaScript function flawlessly in FireFox, yet fails completely in other web browsers?

When it comes to browsing, FireFox is my go-to browser, especially for testing out my website Avoru. However, I recently encountered an issue when checking the functionality of my code on other major browsers like Google Chrome, Opera, and Safari. It seems ...

Display input field in AngularJS when radio button is selected

My JavaScript array looks like this: $scope.quantityMachines = [ { 'snippet' : 'One' }, { 'snippet' : 'Two' }, { 'snippet' : 'Three or more', 'extraField' : true }, { ' ...

Empty Canvas: Google Charts Graph Fails to Populate

I am currently using mysql, php, and javascript to display a curve chart. The issue I am facing is that the chart appears blank. google.load('visualization', '1.0', {'packages':['corechart']}); google.setOnLo ...

Implementing a two column stacked layout with Susy, similar to the design of Twitter's interface

Having worked extensively with Susy, I recently encountered a unique use case that has left me puzzled. To illustrate my point, let's take Twitter as an example. If we observe their website layout, they have a standard three-column design with a brea ...

The positioning of CSS arrows using the "top" attribute is not relative to the top of the page when using absolute values

I am currently working on positioning the arrow in the screenshot using TypeScript calculations. However, I am facing an issue where the position is being determined based on the top of the black popup instead of the top of the screen. From the top of the ...

Looking to switch div visibility upon button click

Looking to create a toggle effect for a content div on the right side of the browser window. I found an example that is similar to what I want, but with a twist - I want to open this panel using an a.class. Instead of relying on IDs, I simply want to targe ...

Calculate the total count of responses within the JSON data returned

Hello all, I need some guidance on calculating the total number of responses in a JSON response that adhere to a specific rule using JavaScript. Here is the JSON response that I am discussing: [ { "InvoiceNumber":"INV0319", "InvoiceOrd ...

Different conversations are taking place concurrently. How can we determine which one is currently being attended to

In my application, multiple dialogs are open simultaneously, each with its own set of shortcuts. It is important to ensure that these shortcuts work correctly based on the focused dialog. Is there a way to determine which dialog is currently in focus? Ed ...

Ways to prevent image toggling when the mouse moves out of it or when the hover effect stops

I'm looking to toggle between two images on mouseover/hover and stop the toggling when hovering stops. Here is the HTML code I have: <div class="fader"> <img src="image1" /> <img src="image2" /> </div> This is the JQuery ...

Close specific child python processes as needed, triggered by a jQuery event

Having trouble managing child processes independently without affecting the main parent process in a web client using jQuery? Look no further. Here's my scenario: I've got a Flask server hosting a basic webpage with a button. Clicking the button ...

Hover Link Overlay [CSS / HTML] - An Alternative Style for Link Interaction

I'm having trouble making an image clickable within a hover effect overlay that displays text and a link. I attempted to turn the overlay into a link, but it wasn't successful. http://jsfiddle.net/cno63gny/ Please disregard the placeholder text ...

Is Node.js truly a single-threaded and non-blocking platform?

As I delve into the world of Node.js, one thing that has caught my attention is the fact that it operates on a single thread and is non-blocking in nature. While I have a solid understanding of JavaScript and how callbacks work, the concept of Node.js bei ...

Safari iOS 8 experiencing issues with loading WebGL image textures

The example mentioned above runs smoothly on all major browsers, including Safari on Mac OS. However, it fails to display the correct image on my iPad running the latest iOS 8. Click here for the example. Similarly, the tutorial provided in the following ...

Unexpected issue encountered while working with json, ajax, and jQuery

Here's the code snippet that I'm working with: $.ajax({type: 'get', mode: 'abort', dataType: 'json', url: 'http://localhost/1.php', data: {}, success: function(res){ alert(res); }, time ...

Steps for creating a dropdown menu that opens when hovering over a selection using Bootstrap Vue

Is there a way to activate the <select> or <b-form-select> dropdown menu when hovering over it, without relying on JQuery or any third-party plugin except for Vue.js? ...

Achieving perfect alignment of two elements using flexbox: centering one and aligning the other to the right

Can you help me with aligning two elements to the center and right edge using flex? I am trying to achieve a layout similar to the image. XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX https://i.sstatic.net/cvmHX.png CSS Styles .flex{ display: flex; justify- ...

"Controller's $watch function fails to trigger when new items are added to an array within a directive

Within my code, I have established a two-way binding variable called publish.selected_tags that connects a directive with a controller. To monitor changes in this variable, I implemented a $watch function within my controller: $scope.$watch('publish ...