Using JavaScript to add a class when hovering over an element

I am trying to customize the ul inside one of my li elements in the nav by adding a class when hovered. However, I am encountering an issue where the menu disappears when I try to click on it after hovering over it. I want to achieve this functionality using vanilla JavaScript.

document.addEventListener('DOMContentLoaded', function () {
    var dropdownItem = document.querySelector('.dropdown-item');
    var dropdown = document.querySelector('.dropdown');

    dropdownItem.addEventListener('mouseenter', function (e) {
        dropdown.classList.add('dropdown-show');
    });
    dropdownItem.addEventListener('mouseleave', function () {
        dropdown.classList.remove('dropdown-show');
    })

})
  .menu {
     list-style: none;
     display: flex;
     width: 30%;
     justify-content: space-between;
     align-items: center;
  }
   .menu li {
     position: relative;
  }
   .menu li a {
     color: #999;
     text-decoration: none;
  }
   .menu .dropdown-item {
     position: relative;
  }
   .menu .dropdown-item .dropdown {
     position: absolute;
     list-style: none;
     top: 5px;
     padding-top: 40px;
     left: -30px;
     visibility: hidden;
     opacity: 0;
     transition: 0.3s;
  }
   .menu .dropdown-item .dropdown .triangle {
     border: 10px solid transparent;
     border-bottom-color: #000;
     width: 0;
     top: 20px;
     left: 50%;
     transform: translateX(-50%);
     position: absolute;
  }
   .menu .dropdown-item .dropdown.dropdown-show {
     opacity: 1;
     visibility: visible;
  }
   .menu .dropdown-item .dropdown li {
     background-color: #000;
     padding: 10px 20px;
     font-weight: lighter;
  }
<ul class="menu">
    <li class="dropdown-item"><a href="#">About Us</a>
        <ul class="dropdown">
            <div class="triangle"></div>
            <li><a href="#">News</a></li>
            <li><a href="#">Our Team</a></li>
            <li><a href="#">History</a></li>
        </ul>
    </li>
    <li><a href="#">Gallery</a></li>
    <li><a href="#">Contact</a></li>
</ul>

Answer №1

Initially, the default Z-index of my li element was mysteriously positioned below another div...

.menu {
    list-style: none;
    display: flex;
    width: 30%;
    justify-content: space-between;
    align-items: center;
    z-index: 999;
}

Now everything is functioning smoothly, and the menu no longer disappears when moving the mouse away from it.

A huge thank you to everyone who provided assistance!

Answer №2

Your SCSS code is quite complex and may not work properly in jsfiddle. However, I managed to achieve the basic functionality you wanted with a small snippet of code.

The issue lies in your implementation where you are attaching the mouseleave event directly to the element (dropdown-item) that displays your dropdown menu. The mouseleave event should actually be applied to the parent container (dropdown).

Below is the corrected code:

document.getElementsByClassName("dropdown-item")[0].addEventListener("mouseover", function(e) {
    const parent = e.target.parentElement;
    if (parent && parent.tagName === "LI" && parent.classList.contains("dropdown-item")) {
        const parent = e.target.parentElement;
        parent.children[1].classList.add("active");
    }
});
    
document.getElementsByClassName("dropdown")[0].addEventListener("mouseout", function(e) {
    e.target.classList.remove("active");
});
.dropdown {
    display: none;
}
    
.active {
    display: block;
}
<ul class="menu">
    <li class="dropdown-item"><a href="#">About Us</a>
        <ul class="dropdown">
            <div class="triangle"></div>
            <li><a href="#">News</a></li>
            <li><a href="#">Our Team</a></li>
            <li><a href="#">History</a></li>
        </ul>
    </li>
    <li><a href="#">Gallery</a></li>
    <li><a href="#">Contact</a></li>
</ul>

* Please note that this is just a basic example for reference. It may not be the most optimal or efficient solution.

Answer №3

Try utilizing the "mouseover" event in place of "mouseenter", and "mouseout" instead of "mouseleave".

Answer №4

Here is an example of how you can achieve this:

<ul class="dropdown" onmouseover="showDropdown($event)" onmouseout="hideDropdown($event)">

function showDropdown(event) {
 event.target.style.display = 'block'; 
 //or you can add a class
 event.target.setAttribute('class', 'active');
}

function hideDropdown(event) {
 event.target.style.display = 'none';
 //or you can add a class
 event.target.setAttribute('class', 'inactive');
}

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

Steps for adding multiple images to a page in a React application:1. Create a

Having trouble displaying images on a React page. I have a directory with 30 images that I want to display on the page (.jsx file). Instead of exporting each image individually, is there a faster way to accomplish this task? Any ideas or suggestions would ...

Integrating Facebook Videos

My website has a collection of video links that open in a fancybox when clicked using jQuery. However, there is an issue where the videos used to play with sound automatically, but now they require manual unmuting. I am unsure of why this behavior changed. ...

Is it possible to access the ID element of HTML using a variable in jQuery?

I have fetched some data from a JSON ARRAY. These values include Value1,Value2, and Value3. Additionally, I have an HTML checkbox with an ID matching the values in the array. My goal is to automatically select the checkbox that corresponds to the value re ...

Experiencing difficulty with parsing an array's json/string version within an Angular controller

Updated question for clearer understanding! I'm currently working on an Angular-Rails application and facing challenges when it comes to parsing an array. One of my ActiveRecord models has an attribute that is an array. Before reaching my Angular app ...

Tips for allowing divs to be dragged and resized within table cells and rows

UPDATE I believe that utilizing Jquery is the most appropriate solution for resolving my issue with the demo. Your assistance in making it work would be greatly appreciated. Thank you. My goal is to develop a scheduler application. The essential functio ...

Troubleshooting problem with list rendering in a Nativescript-vue GridLayout

As a newcomer to nativescript, I am utilizing GridLayout in an attempt to optimize layout nesting for better performance. In my template, I have an image followed by a vertical list of four items next to it. However, only the first item on the list is visi ...

Is it possible to make a link_to, which is essentially a normal <a href>, clickable through a div that is also clickable?

I am currently dealing with a clickable div element which has a collapse functionality, and there is also a link placed on top of it: <div class="panel-group" id="accordion"> <div class="panel panel-default"> <div class="panel-h ...

Insert the object into a designated location within a multi-dimensional array

I've integrated a tree view into my Angular project and I'm looking to add an object to a specific position within an array. array const TREE_DATA: TreeNode[] = [{"name":"Demo","id":"demo_1","children ...

To properly display text strings in your application, ensure they are enclosed within a <Text> component in React Native. This is crucial

I recently integrated the react-native-login-screen package into my React Native project. Below is the code snippet that I used: import React, { Component } from "react"; import { Text, StyleSheet, View, Button, TouchableOpacity } from "reac ...

Is it possible to change the background color of a MUI theme in ReactJS by using Css

Currently, I am utilizing Material UI to create a theme that is functioning correctly. However, upon adding <CssBaseline/> to the App.js file, it unexpectedly changes the background color to white instead of the intended #1f262a specified in the inde ...

The ng-click functionality is not functioning as expected within the directive

Take a look at this snippet of my HTML: <section ng-controller="GalleryController as gallery"> <nav footer-directive></nav> </section> This is the GalleryController I'm using: angular .module('myapp') ...

Enhancing the appearance of an image upon hovering in ReactJS: A step-by-step guide

My issue arises from my desire to border an image and display a Card with information upon hovering, but the problem is that this style is being applied to all images rather than just the one being hovered over. After pulling data from a movie API, I stor ...

"JQuery enables the dynamic cloning of form elements, allowing for attribute adjustments that can be easily reverted

I've been grappling with a puzzling issue recently. I used jQuery to clone a form and assigned IDs to the form elements to increase incrementally with each clone. However, following server validation errors (using Laravel), the IDs of the elements rev ...

The ajax function does not provide a response

Can you help me figure out why this JavaScript function keeps returning 'undefined'? I really need it to return either true or false. I've included my code below: function Ajax() { var XML; if(window.XMLHttpRequest) XML=new ...

Looking to display several charts on a single page with varying datasets?

I have successfully integrated a doughnut chart plugin into my website. However, I would like to display multiple charts on the same page with different data sets. Below is the code snippet for the current chart being used: This is the chart I am using & ...

Sending table data with files or input string data to the server in .NET ASPX web forms is not allowed

When the add button is clicked, the product type, name, and file are added to the table. The variables are declared globally. document.getElementById("addBtn").addEventListener("click", function () { var entryExists = false; var documentName = doc ...

What is the method for activating the on collapse event with a bootstrap navbar?

I am encountering a common issue with collapsing the navbar on smaller screens and triggering an event when the collapse button icon is clicked. Despite my efforts to find a solution, I have been unsuccessful in using the following JavaScript code: $(&apos ...

What are some ways to incorporate JQuery with getElementById?

i am trying to retrieve all input elements within a form using JavaScript formEditable = document.getElementById("formid").getElementsByTagName("input"); However, I would like to achieve the same result using jQuery instead formEditable = $("#formid").f ...

Rails assets folder is not directed to the specified directory in the layout file

I have a dilemma in the application layout where I'm referencing assets (js, css, and img) in the public/assets/... directory. For example: <link href='assets/images/meta_icons/apple-touch-icon-144x144.png' rel='apple-touch-icon-pre ...

Adjust the navigation menu to display or hide as the page is being scrolled

Implementing an offset to display/hide the navigation menu when the page is scrolled 100px. Attempted to modify from lastScroll = 0 to lastScroll = 100 but it did not work as expected. Jquery: Fiddle // Script lastScroll = 0; $(window).on('scroll&ap ...