Ways to showcase contents inside a specific div when hovering with a mouse

I am working with a div structure that includes menus and items within each menu.

<div id="navigate">
   <div class="menu">
       <div class="group">Mail</div>
       <div class="item">Folders</div>
       <div class="item">Messages</div>
   </div>
   <div class="menu">
       <div class="group">Contacts</div>
       <div class="item">Friends</div>
       <div class="item">Work</div>
   </div>
   <div class="menu">
       <div class="group">Setting</div>
       <div class="item">General</div>
       <div class="item">Account</div>
   </div>
</div>

Currently, only items with the class 'group' are visible, and all other items are hidden. I would like to modify the code so that when hovering over a specific menu div, only the items of that particular menu appear.

I have the following code in place:

function initialise()
{
    hideAllItems();

    setMouseOvers();
}

function hideAllItems()
{
    var nav = document.getElementById("navigate");
    var items = nav.getElementsByClassName("item");

    for(var i = 0; i < items.length; i++)
    {
        items[i].style.visibility = "hidden";
        items[i].style.display = "none";
    }
}

function setMouseOvers()
{
    var nav = document.getElementById("navigate");
    var menuArr = nav.getElementsByClassName("menu");

    for(var x = 0; x < menuArr.length; x++)
    {
        var itemArrs = menuArr[x].getElementsByClassName("item");
        
        menuArr[x].onmouseover=function(){ show(itemArrs); };
        menuArr[x].onmouseout=function(){ hide(itemArrs); };
    }
}

function show(itemArr)
{
    for(var i = 0; i < itemArr.length; i++)
    {
        itemArr[i].style.visibility = "visible";
        itemArr[i].style.display = "block";
    }
}

function hide(itemArr)
{
    for(var i = 0; i < itemArr.length; i++)
    {
        itemArr[i].style.visibility = "hidden";
        itemArr[i].style.display = "none";
    }
}

Although the code works, it only displays the items under the 'General' and 'Account' menus, regardless of which menu I hover over. I suspect there is an issue with the code, but I'm unsure of how to correct it without making changes to the HTML structure. Any suggestions would be appreciated!

Answer №1

If you're on the hunt for a solution that doesn't involve javascript, consider a straightforward CSS approach like this:

.group:hover ~ .item {
    display: block;
}

Check out this Working Fiddle

Just keep in mind that this method may not work on older versions of Internet Explorer (< 8), so it's important to consider your target audience before incorporating it.

Answer №2

Have you considered utilizing CSS for this solution? Check out this demo: DEMO

.menu .item{
  display:none;
}

.menu:hover .item{
  display:block;
}

Answer №3

Since you specifically requested a solution using JavaScript only without any changes to HTML or CSS, I have a suggestion that might help:

The issue lies in the use of "itemArrs" within an anonymous function, where only the most recently declared "itemArrs" is utilized for all instances. Instead, consider using "this" keyword.

For instance:

...
groups[x].onmouseover=function(){ show(this); };
...

Furthermore, you can update the "show" function to:

function show(item) {
  var items = item.parentNode.getElementsByClassName("item");
  ...

If you are interested, a comprehensive JavaScript-only solution that addresses these issues can be accessed through the following link: http://jsfiddle.net/Wn4d4/3/

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

How to choose a javascript drop down using selenium?

Here is the HTML code for a JavaScript drop-down menu that contains various options, including "All Resumes". I am attempting to select this option using Selenium WebDriver: <div id="resume_freshness_container"> <div class="dropdown_small_wrapper ...

Can we iterate through a specific set of object attributes using ng-repeat?

Imagine I have the following: $scope.listOfAttributes = ["someThings", "yetMoreThings"] $scope.whatever = { someThings: "stuff", otherThings: "Also stuff", yetMoreThings: "still stuff" }; Can I achieve something like this: <ul> ...

The page is not able to be uploaded successfully, receiving a HTTP 200 status

Currently, my application is running in Express and I have a button that sends a POST request to the server. After receiving a 200 OK response, the HTML page is displayed. The issue I am facing is that even though I can see the HTML payload in Firebug, my ...

Is it possible to have the ShowHide plugin fade in instead of toggling?

I'm currently utilizing the ShowHide Plugin and attempting to make it fade in instead of toggle/slide into view. Here's my code snippet: showHide.js (function ($) { $.fn.showHide = function (options) { //default variables for the p ...

Using radio buttons to toggle the visibility of a div element within a WordPress website

I am currently working on creating a WordPress page using the custom page tool in the admin interface. My goal is to have 3 radio buttons, with 2 visible and 1 hidden. The hidden button should be automatically checked to display the correct div (although ...

Oops! Next JS encountered an unhandled runtime error while trying to render the route. The

I keep receiving the error message Unhandled Runtime Error Error: Cancel rendering route Within my navBar, I have implemented the following function: const userData={ id:1, email: "", name: "", lastName: "", ...

What is the method for specifying the content type when generating a signed URL for an object in AWS S3?

I am trying to generate a signed URL with a custom content-type, but I am encountering an issue when attempting the following: s3.getSignedUrl('getObject', {Bucket: AWS_BUCKET_NAME, Key: 'myObjectsKey', ContentType: 'image/png&apos ...

Simple method for sending a JavaScript array or its data to a servlet utilizing jQuery's ajax() functionality

Seeking advice on passing data from a Javascript array to a servlet using the ajax() method of jQuery. Is there a straightforward way to accomplish this task? The index values in the array are meaningful numbers that are not in order, which complicates th ...

Tips for aligning the button and search bar in the center:In order

Currently still learning HTML, I'm facing an issue with centering a button and a search bar that are positioned beside each other. Despite trying multiple methods, I haven't been successful in achieving the desired centered layout while keeping t ...

When the enter key is pressed, the form will be submitted and the results will be displayed in a modal window without

Behold, my unique form! It lacks the traditional <form></form> tags. <input id="query" name="query" style="font-size: 18pt" id="text" data-email="required" type="text" placeholder="Search Here from <?php echo $row['no']."+"; ?& ...

I'm having trouble with my useState in React/NEXTjs because it's not adding onto the result of a socket.io event from the server, it's simply

Frameworks used: Next.js, Socket.io, React I am currently working on a straightforward messaging application. The main concept involves emitting a message typed by a user, sending that message to the server, and then broadcasting it back to all clients th ...

Error encountered while creating SvelteKit: The module 'intl-messageformat' that was requested is in CommonJS format

Encountering an error during production build. Here's the output of npm run build executed on Node v16.20.1 npm run build > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1c7a6c6a317a757278796e5c2c322c322d">[email&# ...

Maintain the selected image

I am working on a program that allows users to choose images and I have given them the pseudo-class. .my_image_class:hover{ border:3px solid blue; -webkit-box-sizing: border-box; } This makes the images bordered in blue when hovered over, giving a "sele ...

Center the panel on the page and decrease its width using Bootstrap

I recently incorporated a Bootstrap panel above a search results table - my first experience working with Panels. This panel contains a form with a select menu, allowing users to filter the list of search results based on their selections. Currently, the ...

TypeScript struggling to recognize specified types when using a type that encompasses various types

I have a defined type structure that looks like this: export type MediaProps = ImageMediaProps | OembedProps; Following that, the types it references are defined as shown below: type SharedMediaProps = { /** Type of media */ type: "image" | "oembed"; ...

Instructions for selecting a checkbox using boolean values

According to the HTML specification, you should use the checked attribute in the <input type="checkbox"> tag to indicate that it is checked. However, I only have a boolean value of either true or false. Unfortunately, I am unable to manipulate the b ...

Spin a sphere within a semicircle using html and css

I have been working on a project to animate a ball inside a crescent shape using HTML and CSS. You can check out my codepen here. However, I am facing an issue where the ball is currently stuck at the top of the crescent. I would greatly appreciate any as ...

Mastering the art of switching between different application statuses in ReactJS

As a newcomer to reactJS, I am exploring ways to make one of my components cycle through various CRUD states (creating object, listing objects, updating objects, deleting objects). Each state will correspond to displaying the appropriate form... I have co ...

Emotion, material-ui, and typescript may lead to excessively deep type instantiation that could potentially be infinite

I encountered an issue when styling a component imported from the Material-UI library using the styled API (@emotion/styled). Error:(19, 5) TS2589: Type instantiation is excessively deep and possibly infinite. Despite attempting to downgrade to typescript ...

Tips for utilizing the getJson method to pass a variable to a PHP file

I need help with my JavaScript code, as I am trying to pass a datastring containing the value "no" to data.php using getJson in order to receive JSON as a response. However, my JavaScript code is not functioning correctly. Below is the code that I have: J ...