Guide to showing a dropdown menu or any div on the right side of the screen

I need help with displaying a menu that should appear from the right edge of the screen.

Previously, I had a script to show the menu where the user clicked. However, for this specific menu, I adjusted the position by subtracting some pixels from the click coordinates. But I am not satisfied with this approach for two reasons:

  • I want the menu to always be displayed at a static distance from the right edge (let's say 10px)
  • I don't want to manually calculate the right edge of the screen and subtract the menu width as it may not work well on different devices.

I tried using right: 10; but it doesn't seem to work as expected. Any suggestions?


$('#cross').on('click', function (e) {

        // coordinates to display the menu
        var top = e.pageY;
        var left = e.pageX;
        left = left - 150;

        // Display the menu 
        $("#cross-menu").css({
            display: "block",
            position: "fixed",
            top: "calc(3.5rem)",
            left: left
        }).addClass("show");

        return false;
    });

Code: https://jsfiddle.net/7ysp46xv/8/

Answer №1

Instead of overloading your jQuery code with unnecessary CSS settings for the dropdown menu, utilize Bootstrap classes which are designed to handle most styling aspects effectively.

By incorporating Bootstrap's existing class called show into your menu via jQuery, you only need to make minor adjustments utilizing a custom class:

#cross-menu.show {
    right: 10px; 
    left:  auto; /* removing the full-screen left position */
    top:   auto; /* removing the position at 100% */
}

To enable this behavior in jQuery, simply apply the show class as follows:

$('#cross').on('click', function (e) {
        $("#cross-menu").addClass("show");
});

Example in Action:

$('#cross').on('click', function (e) {
        $("#cross-menu").addClass("show");
});
.hamburger {
    height: 80%;
    width: 2rem;
    border: 1px solid white;
    padding: 0px 5px;
    border-radius: 5px;
}

.hamburger div {
        margin: 0.4rem 0px;
        border: 1px solid white;
        background-color: white;
        border-radius: 5px;
}

.link-simple {
  cursor: pointer;
}

#cross {
  cursor: pointer;
}

#cross-menu {
  background-color: gray;
  color: white;
}
#cross-menu.show {
top:auto;
right:10px;
left:auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"><html>
  <body>
    <nav class="navbar navbar-dark bg-dark justify-content-center text-light" style="height: 3.5rem;">

    <!-- Hamburger Menu-->
    <div class="col-2 col-sm-4 align-content-start">
        <div class="hamburger link-simple">
            <div></div>
            <div></div>
            <div></div>
        </div>
    </div>

    <!-- Topic Name -->
    <div class="col-9 col-sm-4 text-center">
        <span class="navbar-brand mb-0 h1">Heading</span>
    </div>

    <!-- User Info / Menu -->
    <div class="col-1 col-sm-4 text-right align-content-end" id="cross">
        X
    </div>

</nav>

<div class="dropdown-menu dropdown-menu-sm" id="cross-menu">
    <a class="dropdown-item pl-3"><i class="fa fa-gear mr-4"></i>Settings</a>
    <a class="dropdown-item pl-3"><i class="fa fa-sign-out mr-4"></i>Logout</a>
</div>


  </body>
</html>

Answer №2

After a bit of experimentation with your code, here's the modified version that worked perfectly:

$("#cross-menu").css({
    display: "block",
    position: "fixed",
    top: "calc(3rem)",
    right: "10px",
    left: 'auto',
    'max-width': "150px",
}).addClass("show");

Answer №3

Give this a shot:

$('button').click(function(){
  $('#menu').animate({
    right: 0
  }, 300);
});

$('li').click(function(){
  $('#menu').animate({
    right: -80
  }, 300);
});
*{box-sizing:border-box;}
body{margin:0;}
button{margin:10vh 0 0 49vw;}
#menu{
  position:fixed;
  width: 80px;
  top:10;
  right: -80px;
}
ul{margin:0;padding:0;list-style-type:none;border:1px solid red;}
li{
  padding: 10px 25px;
  border:1px solid green;
}
li:hover{
  cursor: pointer;
  background: #ccc;
}
aside{
margin-top:10vh;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="menu">
  <ul>
     <li>One</li>
     <li>Two</li>
     <li>Three</li>
  </ul>
</div>
<button>Show Menu</button>
<aside>Insert links inside the LIs to make a menu</aside>

Answer №4

My suggestion for solving your issue is to avoid using a fixed position for dropdowns unless absolutely necessary. Instead, consider using absolute positioning.

In regards to your specific requirement, rather than subtracting the left width, you can use left:auto; and right:5%; to accommodate different device widths.

YOUR CODE: position: "fixed", top: "calc(3.5rem)", left: left,

CHANGES I SUGGEST: position: "absolute", top: "calc(3.5rem)", left: "auto", right: "5%"

I hope these suggestions are helpful in resolving your problem.

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

Modifying the background color in HTML to match user input: A step-by-step guide

Currently, I am in the process of developing my website to allow users to choose a color using a color selector tool. Once they select a color, the background of the webpage will change accordingly. Here is my current progress: function adjustColor() { ...

Preventing hyperlinks within a table from being recognized as the selected table row

I encountered a small issue while working on a webpage where clicking on a link within a table cell causes the entire row to be marked as clicked. However, I want only the link to trigger the click event, not the entire cell. You can view the jsfiddle he ...

Obtain the Xpath for the element with a certain tag located closest to the given element in its immediate surrounding

Within my HTML document, I have a specific element with an id of uniqueId. There are multiple nested tags surrounding this element, and I am trying to retrieve a particular tag that is closest to it. For example: <div> <div> ...

Engaging Resources for Introducing Children to Javascript Programming

Anyone have recommendations for a physical book designed to help children learn programming using Javascript? I've come across the question "Best ways to teach a beginner to program" on Stack Overflow, but it's more focused on Python and doesn&a ...

Code in jQuery or JavaScript to retrieve precise node information for the currently selected form field, text, or image on a webpage

Looking to retrieve specific information about the item that has been clicked on a web page using jquery. The clickable item could be a form element (like a checkbox, text box, or text area) or a section of text within a paragraph, div, list, or image... ...

Using HTML strings in JavaScript code

I am currently working on a basic modal feature where I pass a string to be displayed as the content of the modal window. Here is a snippet of the script I am using: $("[id^='mod_']").click( function() { var line1 = $(this).attr("d ...

How can you link a Razor Function to a JavaScript Variable?

Trying to incorporate a Razor C# Function into a JavaScript Function has been a challenge for me. While it's simple to do in HTML, I'm encountering compilation errors when attempting it in JavaScript. I've experimented with the <text> ...

Aligning images vertically within floated elements

I'm struggling to vertically align some images to the bottom within floated elements, and I just can't seem to make it work. Check out this JSFiddle example. You'll notice that the images are currently aligned to the top. http://jsfiddle.n ...

The JavaScript code for summing two numbers is not functioning as expected

My HTML code takes a user input number, performs a calculation using a formula, and displays the output. The chosen input is inserted into the formula, and the result is added to the original number. However, there seems to be an issue with adding decimal ...

Sending a parameter to a form within Edge Animate

I'm facing an issue where I need to pass a variable to a form from Edge Animate. Here's the current instruction snippet: sym.$("form").append('<iframe width="100%" height="100%" src="login_PRA.php?v_id="vidn frameborder="0" scrolling="no ...

Unable to Utilize Custom Colors in Tailwind CSS within NextJS

I am currently experimenting with NextJs and Tailwinds CSS for a new project. However, I keep encountering an error when attempting to apply a custom background color: Failed to compile ./styles/globals.css:7:12 Syntax error: /Users/anishkunapareddy/Deskto ...

Steps for showcasing stars (1-5) based on the data stored in the database

I recently completed a project where I created a user achievement page that displays their progress. Within the page, there is a table containing the user's level. The table structure looks like this: Users( id, username, password, sum_score, level) ...

The background image is not displaying correctly on mobile devices

I'm struggling to make the image fit the entire screen on a mobile device using the code below. Interestingly, it displays correctly on my personal computer. #topContainer { height:1048px; width: 100%; padding: 0; margin: 0; } #div1 { ...

Binding data to a dropdown menu

I'm working on a jQuery function that retrieves all teams from a service. How can I bind this data to a select box? function FetchTeams() { $.support.cors = true; var jqxhr = $.getJSON('http://localhost/Service.svc/GetTe ...

When attempting to parse a JSON feed with jQuery and innerHTML, the data fails to display

Having trouble parsing a JSON feed using jQuery and innerHTML, but for some reason it's not working as expected. No errors are being displayed in the console and the feed itself is functioning properly. Not quite sure why this issue is occurring. < ...

Is there a way to direct ASP.NET Ajax BeginForm?

I've been following various tutorials on how to submit a form using Ajax.BeginForm() notation, and everything seems straightforward. However, despite implementing AJAX, the form still redirects to display the result instead of replacing the content wi ...

Having trouble with adding data from an array of objects to an HTML element using jQuery's each method

I am currently facing an issue with looping through an array of objects using $.each in jQuery and trying to append the values to an <li>. Here is the relevant jQuery code: $(".sidebar").empty().append("<div>" + "<h5>Student Info</ ...

Customize the text color across all sections of the application in ExtJS 6

I am looking to update the text color across my entire application. Currently, it's gray and I would like to change it to black. The platform I am working with is classic. I came across this code snippet in CSS: .x-body { margin: 0; -webkit-f ...

Tips for grabbing the "Leave Page" button for unrecorded modifications within Firefox?

Currently, I am developing an application where it is essential to detect when the user receives a modal dialog: The message on the page says: "Please confirm that you wish to leave - any unsaved data will be lost." In addition, I need to automatically ...

Jquery auto-suggest form validator

I have implemented a search dropdown menu using jQuery. Everything is working fine, and the 'not match' message displays properly when entering data that does not match any items. However, if I select an item from the dropdown and then modify it ...