Click on the sidebar to reveal the dropdown menu

I have been working on a project and have successfully created a navbar with a dropdown menu that includes a hover effect.

Now, I am attempting to implement a click event to open and close the dropdown's submenu, but unfortunately, it is not working. I am only utilizing HTML and CSS for this task.

Currently, the dropdown opens on hover, but my goal is to:

open and close the drop-down with a click event.

Here is my code:

/* define a fixed width for the entire menu */
.navigation {
  width: 300px;
}

/* reset our lists to remove bullet points and padding */
.mainmenu, .submenu {
  list-style: none;
  padding: 0;
  margin: 0;
}

/* make ALL links (main and submenu) have padding and background color */
.mainmenu a {
  display: block;
  background-color: #CCC;
  text-decoration: none;
  padding: 10px;
  color: #000;
}

/* add hover behaviour */
.mainmenu a:hover {
    background-color: #C5C5C5;
}

/* when hovering over a .mainmenu item,
  display the submenu inside it.
  We're changing the submenu's max-height from 0 to 200px;
*/

.mainmenu li:hover .submenu {
  display: block;
  max-height: 200px;
}

/*
  We now override the background-color for .submenu links only.
  CSS reads down the page, so code at the bottom will overwrite the code at the top.
*/

.submenu a {
  background-color: #ddd;
}

/* hover behaviour for links inside .submenu */
.submenu a:hover {
  background-color: #993;
}

/* this is the initial state of all submenus.
  We set it to max-height: 0 and hide the overflowed content.
*/
.submenu {
  overflow: hidden;
  max-height: 0;
  -webkit-transition: all 0.5s ease-out;
}
<nav class="navigation">
  <ul class="mainmenu">
    <li><a href="">Home</a></li>
    <li><a href="">About</a></li>
    <li><a href="">Products</a>
      <ul class="submenu">
        <li><a href="">Tops</a></li>
        <li><a href="">Bottoms</a></li>
        <li><a href="">Footwear</a></li>
      </ul>
    </li>
    <li><a href="">Contact us</a></li>
  </ul>
</nav>

Answer №1

To create a toggleable sub menu, you can utilize a checkbox (<input type="checkbox">) along with the adjacent sibling combinator (+). Transform the link (a) into a label element. Assign the label's for attribute to the input's id, and then conceal the input by setting its display property to none.

/* Set a fixed width for the entire navigation menu */

.navigation {
  width: 300px;
}


/* Remove bullet points and padding from our lists */

.mainmenu,
.submenu {
  list-style: none;
  padding: 0;
  margin: 0;
}


/* Style all links in the main menu with padding and background color */

.mainmenu a,
.mainmenu label {
  display: block;
  background-color: #CCC;
  text-decoration: none;
  padding: 10px;
  color: #000;
}

.mainmenu input {
  display: none;
}


/* Add hover effect */

.mainmenu a:hover {
  background-color: #C5C5C5;
}


/* Show the submenu when hovering over a .mainmenu item
by changing the max-height of the submenu from 0 to 200px */

.mainmenu :checked+.submenu {
  display: block;
  max-height: 200px;
}


/* Overwrite the background-color for .submenu links only */

.submenu a {
  background-color: #ddd;
}


/* Hover effect for links inside .submenu */

.submenu a:hover {
  background-color: #993;
}


/* Initial state of all submenus:
set max-height to 0 and hide overflowed content */

.submenu {
  overflow: hidden;
  max-height: 0;
  -webkit-transition: all 0.5s ease-out;
}
<nav class="navigation">
  <ul class="mainmenu">
    <li><a href="">Home</a></li>
    <li><a href="">About</a></li>
    <li><label for="products">Products</label><input type="checkbox" id="products">
      <ul class="submenu">
        <li><a href="">Tops</a></li>
        <li><a href="">Bottoms</a></li>
        <li><a href="">Footwear</a></li>
      </ul>
    </li>
    <li><a href="">Contact us</a></li>
  </ul>
</nav>

Answer №2

This is the answer to your problem

/* To toggle between hiding and displaying dropdown content when button is clicked */
function showDropdown() {
  document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown if user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {
    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}
.navigation{
width: 300px;
}

.mainmenu,
.submenu {
  list-style: none;
  padding: 0;
  margin: 0;
}

.mainmenu a {
  display: block;
  background-color: #CCC;
  text-decoration: none;
  padding: 10px;
  color: #000;
}

.mainmenu a:hover {
  background-color: #C5C5C5;
}

/**/

.dropbtn {
  background-color: #ccc;
  color: #000;
  border: none;
  cursor: pointer;
  padding: 10px;
  display: block;
}

.dropbtn:hover, .dropbtn:focus {
  background-color: #ccc;
}

.dropbtn:hover{
 background-color: #C5C5C5;
}

.dropdown {
  position: relative;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #ddd;
  min-width: 160px;
  overflow: auto;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
  width: 300px;
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.dropdown a:hover {background-color: #993;}

.show {display: block;}
<nav class="navigation">
  <ul class="mainmenu">
   <li><a>Home</a></li>
    <li><a>About</a></li>
     <div class="dropdown">
      <li onclick="showDropdown()" class="dropbtn">Products</li>
       <div id="myDropdown" class="dropdown-content">
         <a>Tops</a>
         <a>Bottoms</a>
         <a>Footwear</a>
       </div>
     </div>
  <li><a href="">Contact us</a></li>
  </ul>
</nav>

You can use JavaScript to implement this solution effectively

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

The style of CSS remains constant within the JSP file

Having trouble updating styles on a JSP page using CSS. Here is the code snippet for linking: <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/Profile.css" /> Initially, the styling wo ...

Prevent any sliding animations of content when the button is triggered

I've implemented a basic slideToggle functionality in jQuery. You can check out the code on JSFiddle here: $(document).ready(function() { $(".panel_button").on('click', function() { $(".panel").slideUp(); var targetPanel = $(thi ...

Several A-frames with a variety of animations

Is there a way to apply multiple animations to one object in A-frame? My goal is to make a gltf model move 5 spaces backwards, and then five spaces to the left once the initial animation is finished. How can I accomplish this task? ...

guidelines for quotes in playframework templates

Looking at the tutorial on Playframework's website, the instructor demonstrates a simple example and eventually includes a javascript (coffeescript) file for creating a dynamic list. In the index.scala.html template file, he adds this code: <scri ...

Items on Bootstrap have been expanded to fit larger screens

I'm currently working on a webpage () and facing an issue with the size of objects on a specific screen resolution. When users click on items in the accordions, multiple information cards are displayed. However, on larger screens, these cards appear ...

Tips for embedding HTML/CSS snippets in backticks when using TypeScript with AngularJS

Does anyone else experience the issue of their Angular 2 templates showing up as gray text in Visual Studio Code? I'm unable to use autocomplete or see my CSS properly. Is this a settings problem or is there a plugin that can solve this? BTW, I am us ...

"An empty image is represented by a red cross symbol with a disappointed expression

Is there a way to prevent Internet Explorer from displaying red crosses when the image is empty? If I have an ASP Image, can I make it invisible and check if it contains any content or not? <asp:Image ID="Image1" runat="server" ImageUrl="Handler.ashx" ...

The margin-bottom CSS class is integrated within Twitter Bootstrap

Is there a standard margin bottom class that can be used? I attempted to use bottom5 like this: <div class="col-lg-2 bottom5"></div> However, it did not have the desired effect. ...

What is the best way to incorporate classes into <li> elements within WordPress?

I'm currently in the process of building my WordPress theme from scratch, but I've run into a roadblock when it comes to adding custom classes to the < li > tags alongside those that are automatically generated by WordPress. Below is the co ...

I am experiencing issues with the visibility of my background on certain mobile browsers

Apologies for repeating a similar question, but I've already tried the solutions mentioned in other posts. On my webpage, I have a table with a background image set using CSS. html { width:100% height: 100%; margin: 0px; padding: 0px; border: none; } ...

What steps should be taken to enlarge a checkbox within a table?

I need help with resizing the checkboxes that are inside a table. When I try using width:###px; height:###px;, it only seems to make them smaller, not bigger. Even when I set the values higher than the default size, the checkboxes stay the same while the d ...

The sticky navigation bar allows for the overlapping of additional div elements

Here is the HTML AND SCSS(SASS) code for a NAVBAR: <div id="navbar"> <ul> <li><a href="#home">Home</a></li> <li><a href="#main">Main</a></li> ...

Using ImageResource in ClientBundle to create an actual <img> element

Is there a way to inform ClientBundle that all images should be actual img elements instead of fake css-background images, as background images are not printed by default in IE9? ...

What is the best way to assign group headings to my Codeigniter view results?

One of the challenges I'm facing in my view is organizing a list like this: <? foreach($services as $service): ?> <tr> <td><?= $service->name; ?></td> <td><?= $service->format; ?></td> < ...

Tips for preventing a page from automatically scrolling to the top after submitting a form

Recently, I set up a form where users can input values. The form is set to submit either on change or when the user hits enter, depending on which value they want to update. However, after the values are submitted, the page automatically jumps back to the ...

Rapid processing of JavaScript upon page load

I recently implemented a dark mode feature on my WordPress site. Here are the four modes I included: 1- Automatically based on user's system settings 2- Light mode 3- Semi-lit mode 4- Dark mode The implementation is in place and functioning perf ...

The integration of a Bootstrap modal within the side bar's rendering

Struggling with a modal appearing inside my side div and can't find any solutions in the bootstrap5 documentation or online forums. https://i.stack.imgur.com/gHsBi.png I just want the modal to display centered on the page with the background fade ef ...

Is your Navbar having trouble readjusting its height?

My navbar is not resizing properly when I shrink the logo image. Here's a link to the Codepen page with the full code: https://codepen.io/gabor-szekely/pen/JeMqQz I'm trying to reduce the size of the "Sino Medical" logo image in the top left co ...

Is it possible to create .html files using the provided list of words?

Can we create .html files from a word list? Check out the example shown in the attached image. Thank you! View Image ...

Properly managing mouseover events on a flipped div: tips and tricks

I created a div that flips when clicked using some HTML and CSS code. It works perfectly in Firefox 39 and Chrome 43. Here is the markup: <div class="flip-wrapper flippable-wrapper" id="fliptest-01"> <div class="flip-wrapper flippable ...