Closing the dropdown menu by directly clicking on the button

I've noticed several inquiries on this platform regarding how to close a drop-down menu by clicking anywhere outside of it.

However, my question is a bit different. I want the dropdown-menu to remain open once clicked, only closing when the user clicks on the button again. Additionally, when the menu is displayed, I want it to push other elements directly beneath it down, such as other buttons. This concept can be seen on various websites and I find it intriguing. I would like to implement something similar but I'm unsure where to start.

This functionality will most likely be achieved with Javascript for simplicity, but I lack the knowledge on how to execute it. Do you have any suggestions or tips?

Your help would be greatly appreciated. Thank you in advance.

Edit: To provide an example of what I mean: Link to jsfiddle ->https://jsfiddle.net/Cerebrl/uhykY/

I aim to move buttons 2 and 3 downward as soon as the first menu is expanded, creating its own space for display. Furthermore, I intend for the menu to only close upon button click, not by clicking outside of it.

Answer №1

To easily implement a slide toggle effect, you can use the toggleSlide method in just two lines of code:

$(function(){
  $('button').click(function(){
    $('ul').slideToggle();
  });
});
ul {
  background: none #FA982E;
  margin: 0;
  padding: 0;
  list-style: none;
  display: none;
}
ul a {
  display: block;
  padding: 5px 20px;
  text-decoration: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
  <button data-toggle="#menu-main" title="Click to toggle">Toggle Menu</button>
</p>
<ul id="menu-main">
  <li><a href="#">Menu item 1</a></li>
  <li><a href="#">Menu item 2</a></li>
</ul>

Answer №2

To make the menu push the content below, you can utilize jQuery's slideToggle method to hide the menu by default:

$('[data-toggle]').on('click', function(e){
e.preventDefault;
    var thisLink = $(this);
    var toToggle = $( thisLink.data('toggle') );
    toToggle.slideToggle(200);
})
* {
    font-family: sans-serif;
}
.toggle-menu a {
    display: block;
    float: right;
    padding: 5px 20px;
    text-align: center;
    background: none #F1B475;
    cursor: pointer;
}
#menu-main {
    background: none #FA982E;
    margin: 0;
    padding: 0;
    list-style: none;
    display: none;
}
#menu-main a {
    display: block;

    padding: 5px 20px;
    text-decoration: none;
}
#menu-main a:hover,
#menu-main a:focus {
    background: none #D0812D;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="toggle-menu">
    <p>
        HELLO
        <a data-toggle="#menu-main" title="Click to toggle">+</a>
    </p>
    
</div>
<ul id="menu-main">
    <li><a href="#">Menu item 1</a></li>
    <li><a href="#">Menu item 2</a></li>
</ul>
<p>
    Other content
</p>

By using normal flow for the menu positioning, it will automatically push down the content below it. Check out this JSFiddle playground for an example.

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

Revamp the jquery.ajax promise or find an alternative solution

I am looking to modify the data from an ajax call and pass it to another plugin's constructor. I believe that by having the plugin options accept either an object for its data or a function that returns the data, I can incorporate a deferred object li ...

Using ion-icon inside a clickable ion-card while applying float: right does not render properly

I am facing an issue with a list of ion-cards that have clickable icons appearing when you hover over them. The problem is that due to the floating nature of the icons, they are not positioned correctly (as shown in the image below) and end up getting cove ...

Encountering an unhandled runtime error while importing the Client component into the server component: The JSON format is invalid, with the error message stating "undefined"

I've been attempting to create a basic counter component that increments the count of a state variable when a button is clicked. To achieve this, I created a separate file named Counter.tsx and placed it in the components folder at the root of my next ...

Is it possible to create a multi-page single-page application using Vue js SSR?

It may appear contradictory, but I struggle to find a better way to express it. When using vue server-side rendering, it seems you are limited to single page applications. However, for various reasons, I require an application with multiple real server-s ...

What steps do I need to take for webpack to locate angular modules?

I'm currently in the process of setting up a basic application using Angular 1 alongside Typescript 2 and Webpack. Everything runs smoothly until I attempt to incorporate an external module, such as angular-ui-router. An error consistently arises ind ...

Developing an Angular 2 Cordova plugin

Currently, I am in the process of developing a Cordova plugin for Ionic 2. The plugin is supposed to retrieve data from an Android device and display it either on the console or as an alert. However, I am facing difficulty in displaying this data on the HT ...

Service for Posting in Angular

I am looking to enhance my HTTP POST request by using a service that can access data from my PHP API. One challenge I am facing is figuring out how to incorporate user input data into the services' functionality. Take a look at the following code snip ...

Ways to conceal a badge using JavaScript

Can anyone help me figure out how to edit the data-count of a badge and hide the badge using JavaScript in a Bootstrap 5 navbar with a stacked Font Awesome icon? I have tried the following: document.getElementsByClassName("p1 fa-stack fa-2x has-badge ...

Tips for properly setting up a loop to effectively showcase all available data

I am encountering a strange issue when trying to display all incorrect answers in a table for each question. For some reason, one of the rows is showing up empty. This problem only occurs with question 2, which happens to have multiple correct answers. I s ...

Determine the quantity of items that meet specific criteria

The initial state of my store is set as follows: let initialState = { items: [], itemsCount: 0, completedCount: 0 }; Whenever I dispatch an action with the type ADD_ITEM, a new item gets added to the items array while also incrementing the count in ...

What is the process for loading a script file from within a component's HTML?

My goal was to include a specific script file in the component html, but I noticed that when I added the script reference within the html itself, the inner script file was not rendered along with the component on the page. Component import { Component } ...

Creating a responsive web design with a user-friendly CSS grid layout

Currently, I am delving into the realm of CSS grid to better comprehend its functionality. In my layout design, there are two menus (colored in red) positioned on either side of a central main content box (colored in blue). As the screen size reduces and ...

What are the specifications for the opacity, width, and height of the background image in Bootstrap's

My current project has specific requirements that I need assistance with: I need the background image of the jumbotron to fit the width of the page and have its height scaled proportionally. The opacity of the jumbotron's background image should be ...

Modify table cell content based on boolean value - HTML

Currently, I am working with a table that displays properties from an object. Is there a simple method to change the text displayed in a cell instead of the true/false values it is currently set to? For example, one of the columns indicates whether the ob ...

The buttons are not resizing to fit the entire table cell

I'm currently working with Bootstrap 4 and trying to place buttons in a table cell for each row. However, the buttons are not expanding to fill the available space and appear squished. This issue persists even when I switch to mobile view. From the p ...

Tips for creating a dynamic route with NextJs 14 API

Looking to start a blog with Next.js 14 and I'm working on defining a function in api/posts/[postSlug]/route.js. How do I access the postSlug parameter within this function? Here's my current function code: // api/posts/[postSlug]/route.js impor ...

Implementing Dual Submit Buttons in Node.js using Express Framework

Struggling with implementing a like and dislike function in my node js app. Currently, I can only do one at a time. Below is the HTML code snippet: <form method="post" name="ratings"> <input type="submit" name="vote" value="like"> < ...

Enable access to the child of Lages and apply CSS to disable it

My current code looks something like this: <label for="billing:postcode" class="required"><em>*</em>Zip/Postal Code</label> I am looking to hide the <em> element from displaying using CSS. How can I achieve this with the dis ...

Utilize data from two distinct JSON sources that are updated at varying intervals, and display the combined results in an ng-repeat

I am currently working on creating a status list that pulls data from two separate JSON sources. The main purpose of this list is to show general information from the first source, while also indicating a status color based on the number of people in the s ...

Setting the `setCustomValidity()` method for dynamically inserted HTML elements Explanation on how to use

I am dynamically adding elements to my view and setting their attributes using the jQuery attr function as demonstrated in the code snippet below: var input = $("<input type='text' name='"+inputFieldName+"' '>"); input.attr( ...