The dropdown menu fails to expand when hovered over

                            <li className={styles.link + " " + styles.hideOnMobile}>
                            <div className={styles.dropdownMenu}>
                                <button className={styles.dropbtn}>Product</button>
                                <div className={styles.dropdownContent}>
                                    <a
                                        href="#"
                                        onClick={this._trackClick.bind(this, "header")}
                                    >
                                        Link 1
                                    </a>
                                    <a
                                        href="#"
                                        onClick={this._trackClick.bind(this, "header")}
                                    >
                                        Link 2
                                    </a>
                                </div>
                            </div>
                        </li>


.dropdownMenu {
    position: relative;
    display: inline-block;
}

.dropbtn {  
    padding: 14px 16px;     
    font-size: 16px;
    border: none;
    outline: none;
    margin: 0;
    &:hover{        
        background-color: $color-active-dark;
        cursor: pointer;
    }   
}

.dropdownContent {

    display: none;
    position: absolute;
    background-color: $color-active-dark;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
    &:hover {
        display: block;
        cursor: pointer;
    }
    a {
        float: none;
        text-align: left;
        padding: 12px 16px;
        text-decoration: none;
        display: block;
        &:hover{
            background-color: $color-active-dark;
            cursor: pointer;
        }
    }
}

I've been working on this code snippet to create a dropdown menu in the top navigation bar. However, I'm facing an issue where the display doesn't change to block when hovering over it as expected. Instead, the color of the product button changes. As I am relatively new to front-end development, any help or suggestions would be greatly appreciated.

Answer №1

To ensure the submenu opens on hover, you can add an extra line of code to your CSS. Here is an example in plain CSS:

.dropdownContent:hover,
.dropbtn:hover + div {
  display: block;
  cursor: pointer;
}

It's important to note that this method is specifically for triggering the dropdown on hover. For touchscreens, a toggle mechanism will require Javascript.

Update:

If you are looking to toggle the dropdown (open/close on click), you can utilize the following JavaScript snippet:

<script>
var Buttons = document.querySelectorAll(".dropbtn");
for (var i = 0; i < Buttons.length; i++) {
  Buttons[i].addEventListener("click", function(event) {
    var Divs = document.querySelectorAll(".dropdownContent");
    var Shown = (this.nextElementSibling.classList.contains("show"));
    for (var j = 0; j < Divs.length; j++) Divs[j].classList.remove("show");
    if (Shown) this.nextElementSibling.classList.remove("show");
    else this.nextElementSibling.classList.add("show");
  });
}
</script>

Add the following CSS at the end of your current navigation CSS:

.dropdownContent {
  display: none;
}
.dropdownContent.show {
  display: block;
}

Please keep in mind that this JavaScript code will only open one dropdown at a time, especially if you have multiple

<li class="link hideOnMobile">
items in your navigation.

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

What is the best way to bring a background image to the forefront?

I am currently working on creating a list of "fake videos" which are essentially images with a play icon on them. My plan is to use the play icon as a background and bring it to the front of the image by adjusting the z-index. However, no matter what I try ...

What is the best way to resize a background image to perfectly fit the visible screen on a mobile device?

When accessing the website on a mobile device, the background image adjusts based on the amount of content on the page. It expands when there is more content and shrinks when there is less. For instance, opening the navigation panel on a mobile device caus ...

What steps can I take to ensure my CSS selector for the element is functioning properly?

Here is an example of some code: <html> <head> <style> .test{ background-color: red; p { background-color: yellow; } } </style> </head> <body> <div class="test"> ...

"Attempting to send JSON data via JsonResult is unsuccessful when trying to send a JSON object directly or using JSON

In my project, I have a class that looks like this: I've created a JsonResult method in the controller which takes an object of this class as a parameter: [HttpPost] public JsonResult NewAreaCode(AreaCode model) { return Json ...

How do you insert a button into a table using react and coreui?

I have implemented a table to display some data: The data is being displayed properly. My goal is to add a remove button on each row of the table. When the button is clicked, an onClick function should be executed to send a remove request to the server a ...

When I modify the CSS "display" property of an element using JavaScript, the page remains unchanged

I have a simple application designed to filter a list by displaying items that match the criteria and hiding the rest. There is a function triggered by an 'input' event on the <input> element. This function modifies the "display" attribute ...

The autoHideDuration feature in Snackbar does not seem to be functioning as expected when implemented

Incorporating a @material-ui snackbar in multiple sections of my reactjs project has resulted in code duplication for the onClose and onClick handlers. To streamline this process, I created a hook to centralize these parameters. However, upon moving the co ...

Sharing various data from Express to Jade is quite simple and can be done

I have a series of variables that are checking against a condition to determine if they return true or false. While I've been able to print these results using console.log, I now need to display them in a jade template. However, I'm encountering ...

The landscape orientation causes the button bar to overflow by 100% of the body height

Imagine the scenario below: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <style type="text/css"> html, body { padding: 0; margin: 0; ...

What is the best way to use regex for splitting an array?

I have a string that I need to convert into an array of objects const str = "Nike (brand|category) shoes(product) for women(o)" Expected result let output = [ { key:"Nike", value:["brand","category"] }, { key:"shoes", value:["product"] }, { ...

Switch the placement of two DIV elements by their corresponding IDs

I am attempting to adjust the position of two divs using jQuery, but I seem to be a bit confused as they are already swapping positions. However, when they do swap, it results in a duplication of the field. I have tried using both insertBefore and insertA ...

Transitioning to EM-Based Media Queries

After the recent resolution of the WebKit page-zoom bug, what are the primary benefits of utilizing em-based media queries over pixel-based ones? Incentive I am offering a reward for my question as many prominent CSS frameworks and web developers use em- ...

Unable to get callback to function properly within request npm

I am facing some challenges with the callback function while using Request npm in my project. The API for users is built with Sailsjs, and I am using Reactjs for the front-end along with Request npm for communication with the API. There seem to be issues w ...

Is it possible to have scope inherit from an object in AngularJS?

Imagine creating an app like this: <script> myArray=<?php echo $array;?>; app={ myArray:myArray, myIndex:myArray.length-1, back:function(){this.myIndex--;console.log("You clicked back");}, forward:function(){this.myIndex++} } ...

Can I use the mouseover event on an image to display a sibling div?

Hi everyone! I'm fairly new to web development and I could really use some advice. I'm trying to implement a mouseenter event on an img tag to show a sibling div, but I'm encountering some strange behavior. The mouseenter event seems to be w ...

I need to retrieve the Instagram follower count for a specific user using JavaScript based on their user ID

I'm looking to design a form that allows users to input their Instagram ID and receive the exact number of followers without the "k" abbreviation. However, I am unsure how to achieve this. Any guidance on how to accomplish this would be greatly apprec ...

Using the input method in JavaScript cannot extract an object property

Recently, I have been working with this JavaScript code provided below. It is essential for me to retrieve the votecount for a game based on user input. function Game(gamename,votes) { this.gamename = gamename; this.votes = votes; }; var lol = ne ...

How can I integrate a Google Maps instance into my Rails views?

I have a file named my_app.js.coffee and it includes the following Google Maps setup: map = undefined initialize = (map) -> myOptions = center: new google.maps.LatLng 39.729001, -94.902342 zoom: 3, mapTypeId: google.maps.MapTypeI ...

The $(document).ready() function triggers as soon as the document is fully

I created a simple webpage with the following HTML: <!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>hi</title> <script type="text/javascript" src="js/jquery-1.8.2.js"></script> <link type="t ...

Discovering the Xpath for a checkbox within a <div><input> combo using Selenium

Is there a way to successfully click on the checkbox with the provided code? I've attempted using the xpaths below, however, they are unable to locate the checkbox and do not display any errors in the console. driver.findElement(By.xpath("//*[@id=&ap ...