What is the best way to ensure that the buttons remain in place once they have been clicked to reveal a drop-down menu?

Is there a way to keep 3 buttons inline and prevent them from moving when clicked to open a submenu? Changing their positions results in them stacking on top of each other. Any help or suggestions would be greatly appreciated, thank you!

Here is the code snippet:

HTML

<button class="menu-trigger btn-1">1</button>
<ul class="menu">
  <li>test</li>
  <li>test</li>
  <li>test</li>
</ul>
<button class="menu-trigger btn-2">2</button>
<ul class="menu">
  <li>test</li>
  <li>test</li>
  <li>test</li>
</ul>
<button class="menu-trigger btn-3">3</button>
<ul class="menu">
  <li>test</li>
  <li>test</li>
  <li>test</li>
</ul>

CSS

.menu-trigger{
    padding: 10px 25px;
    font-family: 'Roboto', sans-serif;
    font-weight: 500;
    background: transparent;
    outline: none;
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;
    display: inline-block;
    color: lightgray;
}

.menu{
    display: none;
}

.menu.open{
    display:block;
}

.btn-1 {
    border: 2px solid yellow;
}

.btn-1:hover {
  background: #000;
  color: #fff;
}

JS

 $(function () {
      $(".menu-trigger").click(function () {
        $(this).next(".menu").toggleClass("open"); // Selects only the next one!
        $(this).html($(this).next(".menu").hasClass("open") ? menu-trigger : menu-trigger);
        return false;
      });
    });

Answer №1

To get your desired layout, you'll need to modify the HTML structure and apply some CSS styles. I've made some changes to your code:

  1. Firstly, wrap each button with its respective menu using <ul>, and wrap them inside <li> elements.
  2. Apply display: inline-block; and position: relative; to each <li> element that wraps the
    <button><ul>...</ul></button>
    .
  3. Set the position of ul.menu to absolute.

Your edited code is provided below:

$(function () {
      $(".menu-trigger").click(function () {
        $(this).next(".menu").toggleClass("open");
        $(this).html($(this).next(".menu").hasClass("open") ? menu-trigger : menu-trigger);
        return false;
      });
    });
.menu-trigger{
    padding: 10px 25px;
    font-family: 'Roboto', sans-serif;
    font-weight: 500;
    background: transparent;
    outline: none;
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;
    display: inline-block;
    color: lightgray;
}

.menu-container {
  list-style: none;
  margin: 0;
  padding: 0;
}

.menu-container > li {
  display: inline-block;
  position: relative;
}

.menu{
    position: absolute;
    left: 0;
    display: none;
}

.menu.open{
    display:block;
}

.btn-1 {
    border: 2px solid yellow;
}

.btn-1:hover {
  background: #000;
  color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul class='menu-container'>
<li>
  <button class="menu-trigger btn-1">1</button>
  <ul class="menu">
    <li>test</li>
    <li>test</li>
    <li>test</li>
  </ul>
</li>

<li>
  <button class="menu-trigger btn-1">2</button>
  <ul class="menu">
    <li>test</li>
    <li>test</li>
    <li>test</li>
  </ul>
</li>

<li>
  <button class="menu-trigger btn-1">3</button>
  <ul class="menu">
    <li>test</li>
    <li>test</li>
    <li>test</li>
  </ul>
</li>
</ul>

I trust this will be beneficial for you.

Answer №2

You might want to consider adjusting the following:

CSS:

  .menu{
    position: absolute;
    top: 100px;
    float:left;
    display: none;
   }

.btn-1 {
   float: left;
   border: 2px solid yellow;
 }

and within your code:

$(function () {
  $(".menu-trigger").click(function () {
      $(".menu").hide();
    $(this).next(".menu").toggleClass("open"); // Only targets the next instance!
    $(this).next(".menu").show();
    $(this).html($(this).next(".menu").hasClass("open") ? menu-trigger : menu-trigger);
  });
});

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

Reposition the div element on mobile devices using media queries

Hello, I'm facing an issue on mobile with my website: dev site Today, I implemented a dropdown menu with flags to allow language switching. However, the dropdown in mobile is appearing under the hamburger nav bar. I was thinking of using media querie ...

Switch up the Thumbnail Image based on the selected category

While testing a shopping site I created, I encountered an issue with changing the banners at the top of the page based on the category the user is viewing. This site is hosted on a server on my localhost, not using wordpress by the way. <div class=" ...

Encountering "net::ERR_EMPTY_RESPONSE" error when making a HTTP PUT request using the HUE API in JavaScript

GET requests are functioning properly. PUT requests made from the API Debug tool are also working correctly. However, both PUT and POST requests, regardless of the data or API URL used, are resulting in the following error: example: OPTIONS net::ERR_ ...

Transmit the data.json file to a node.js server using Postman

Hi there, I have a file named data.json saved on my desktop that I want to send to a node.js function. The contents of my data.json file are structured as follows: [{"key":"value"}, {same key value structure for 8000 entries}] This fil ...

Screen proportions altered - Background image disappearing | Unusual occurrences |

If you look at my site everything seems to be ok, ... untill you minimize the website. A horizontal scrollbar appears and when you use that scrollbar, you will see that my image has vanished. My Website I made that image responsive...so i have no idea wh ...

Angular has surpassed the maximum call stack size, resulting in a Range Error

I am facing an issue while trying to include machine detail and a button bar in my app. Interestingly, this setup has worked perfectly fine in other parts of the application but is causing errors in the core module. Here is the error message main.ts impo ...

Mistake while defining a global variable within an HTML file and utilizing it

In my HTML document, I have set a global variable like this: <script type="text/javascript"> var total; </script> However, when I try to use this variable, I encounter an error stating that it cannot be used in this context. To resolve this ...

When scrolling back to the top of the page, the data-spy feature does not re-highlight the "Home" anchor

After experimenting with Data-spy to change the active anchor while scrolling, I encountered an issue. Upon scrolling back up to the top of the page from the about section, the "Home" anchor failed to re-activate. How can this be fixed? I attempted to rem ...

What is the best way to eliminate all borders from a select box?

Is there a way to completely remove all borders from the selectbox using either CSS or JQuery? The code snippet is as follows: <select id="doctor_ch"> <option value="1" selected>One</option> <option value="2">Two</option& ...

Tips for creating a responsive HTML5 form

I am trying to center and make my form responsive. Can you help me achieve that with the code below? HTML5 Code <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html ...

When implementing the Dropdown Picker, it is important to avoid nesting VirtualizedLists inside plain ScrollViews for optimal

Currently, I am utilizing the RN library react-native-dropdown-picker. However, when I enclose this component within a ScrollView, it triggers a warning: "VirtualizedLists should never be nested inside plain ScrollViews with the same orientation because ...

Implementing dynamic attribute id addition to select option

Here's the code snippet I'm currently working with: Included HTML <select id="drop_opts"> <option>1<option> <option>2<option> <option>3<option> </select> ...

"XMLHttpRequest 206 Partial Content: Understanding the Importance of Partial

I need help with making a partial content request using an XMLHttpRequest object in JavaScript. Currently, I am trying to load a large binary file from the server and want to stream it similar to how HTML5 video is handled. While setting the Range header ...

Exploring the data-* attribute in jQuery

Currently, I have a form structured as follows: <div data-role="page" data-last-value="43" data-hidden="true" data-bind='attr : {"name":"John"}'></div> My objective is to modify the name attribute from "John" to "Johnny". I am att ...

I need to securely store HTML formatted strings in a database

Currently, I am using a react quill component that outputs HTML content like this: EXAMPLE: <p><br></p><p>fsdafsd</p><p>fsdfsda</p><p>fsdafsad</p I want to store this content in a database. However, I ...

"Learn the process of setting a variable in ng-model within an input field based on a specific condition

I need to dynamically assign an ng-model variable based on a condition. For instance: <input type="text" ng-model="item.model[multilang]" > The $scope.multilang variable can be set to either "ENG", "JP" (languages) or false. So, when multilang = "E ...

Ways to center Bootstrap panel in the middle of a webpage

Is there a way to center this entire panel on the web page? I could use some guidance with this. Does anyone have recommendations for a good book to learn Bootstrap design? <div class="panel panel-default" style="max-width:500px;margin-left:auto;margi ...

Getting the href values of dynamically changing links with Selenium in Python: A step-by-step guide

Is there a way to extract all hrefs(links) located in anchor tags using JavaScript code with Selenium Python, especially when these links are dynamically updated? The tag I am trying to click on is as follows: enter image description here I have managed t ...

Reducing image size using CSS can result in blurry images on multiple web browsers

Encountering challenges with downscaled images in multiple browsers... The images must be downscaled to adapt to the browser size. Here is the code snippet: #pic-holder img { -moz-transform: rotate(0deg); /*image-rendering:-webkit-optimize-contras ...

Tips on getting rid of the excess margin added by Android WebView printing

We have been attempting to print content from a webview via Google Cloud Print, but no matter what steps we take, the resulting printout always includes an unwanted margin. Is there a solution to eliminate this margin? We have tried: <body style="marg ...