Tips for creating a hidden tab that only appears when hovered over

When hovering over the link tag .cat-link a.navlink, each subcategory tab .subcategories div is displayed.

However, I would like to hide all tabs initially and have them appear only when hovered over with the mouse. Once the mouse is removed, I want the tabs to disappear.

Currently, the first tab is always visible even after refreshing the page.

Is there a way to keep all tabs hidden until they are hovered over? Thank you!

const tabBtn = document.querySelectorAll('.category .cat-link .navlink');
const tab = document.querySelectorAll('.subcategories div');

        function tabShow(panelIndex) {
            tab.forEach(function(node) {
                node.style.display = "none';
            });
            tab[panelIndex].style.display = "block";
        }

        tabShow(0);
.subcategories {
    float: left;
    position: relative;
}

.subcategories div {
    width: 100px;
    height: 100px;
    position: absolute;
    background: red;
    display: none;
}
<div class="cat-link">
      <a href="#" onmouseover="tabShow(0)" class="navlink computer">
          <i class="fa fa-tv"></i>
          <span>Computer & Gaming</span>
      </a> 
      <a href="#" onmouseover="tabShow(1)" class="navlink phone">
          <i class="fa fa-mobile-alt"></i>
          <span>Mobiles & Tablets</span>
      </a> 
      <a href="#" onmouseover="tabShow(2)" class="navlink elect">
          <i class="fa fa-computer-speaker"></i>
          <span>Electronics</span>
      </a> 
</div>

<div class="subcategories">
     <div class="computer-sub">
         1
     </div>
     <div class="mobile-sub">
         2
      </div>
     <div class="electronics-sub">
         3
     </div>
</div>

Answer №1

When an item is hidden with display: none;, it does not have a visible bounding box, which means hovering detection is not possible.

Consider using opacity as an alternative solution.

const tabBtns = document.querySelectorAll('.category .cat-link .navlink');
const tabs = document.querySelectorAll('.subcategories div');

function showTab(panelIndex) {
    tabs.forEach(function(element) {
        element.style.opacity = "0";
    });
    tabs[panelIndex].style.opacity = "1";
}

showTab(0);

Answer №2

To achieve the desired effect, consider creating two distinct CSS classes. One class should include the property visibility: hidden;, while the other should include visibility: visible;. By utilizing methods such as

node.classList.add("hidden-element");
and
node.classList.remove("visible-element");
, you can dynamically apply or remove these classes to any HTML element.

Answer №3

If you're looking for a simple way to achieve this, consider breaking down your current tabShow function into two separate functions: tabShow for displaying content and tabHide for hiding it:

function tabShow(panelIndex) {
    tab[panelIndex].style.display = "block";
}

Define the tabHide function to hide the content:

function tabHide(panelIndex) {
    tab.forEach(function(node) {
        node.style.display = "none";
    });
}

Remember to remove tabShow(0); from your JS code. Instead, add onmouseout="tabHide()" alongside each existing onmouseover="tabShow(x)" event.

Here's an example snippet that demonstrates how to implement these changes:

const tabBtn = document.querySelectorAll('.category .cat-link .navlink');
const tab = document.querySelectorAll('.subcategories div');

        function tabShow(panelIndex) {
            tab[panelIndex].style.display = "block";
        }
        function tabHide(panelIndex) {
            tab.forEach(function(node) {
                node.style.display = "none';
            });
        }
.subcategories {
    float: left;
    position: relative;
}

.subcategories div {
    width: 100px;
    height: 100px;
    position: absolute;
    background: red;
    display: none;
}
<div class="cat-link">
      <a href="#" onmouseover="tabShow(0)" onmouseout="tabHide()" class="navlink computer">
          <i class="fa fa-tv"></i>
          <span>Computer & Gaming</span>
      </a> 
      <a href="#" onmouseover="tabShow(1)" onmouseout="tabHide()" class="navlink phone">
          <i class="fa fa-mobile-alt"></i>
          <span>Mobiles & Tablets</span>
      </a> 
      <a href="#" onmouseover="tabShow(2)" onmouseout="tabHide()" class="navlink elect">
          <i class="fa fa-computer-speaker"></i>
          <span>Electronics</span>
      </a> 
</div>

<div class="subcategories">
     <div class="computer-sub">
         1
     </div>
     <div class="mobile-sub">
         2
      </div>
     <div class="electronics-sub">
         3
     </div>
</div>

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

Receiving encoded characters in the response

URL: I have encountered an issue where I am trying to retrieve the PDF file from the URL above using code. In tools like Postman or Insomnia, I am able to see the output as expected in PDF format. However, when I attempt it with code, I am receiving rando ...

Utilize the size of the array as a variable

I have a question regarding the use of the length of an array as an integer value in JavaScript. Here is the code snippet: var counter = 0; var bannerLinks = document.getElementsByClassName("bannerlink"); var linkCount = bannerLinks.length; va ...

Utilizing loops for data selection and presentation within a div using MySQL and PHP

I currently have a large table in my MySql database containing numerous rows of records (referred to as the existingbankproducts table): Below is the code I am using to select data from the database: $stmt2 = $DB_con->prepare("SELECT * FROM applicantp ...

Issues encountered while trying to access a child state using Ionic and UI-Router

My current setup includes the following parent states: // Abstract state for tabs directive .state('tab', { url: "/tab", abstract: true, templateUrl: "templates/tabs.html", controller: "TabCtrl" }) // Each tab has its ow ...

CssLint detected an unfamiliar property: "fill"

Currently, I am updating the color of an SVG path using CSS: .compute .svg path { fill: #fff; } The functionality is working properly, however, during a CSSLint check, I received this warning: Unknown property: "fill" I am unsure if this is an erro ...

Unveiling the magic: Dynamically displaying or concealing fields in Angular Reactive forms based on conditions

In my current scenario, there are three types of users: 1. Admin with 3 fields: email, firstname, lastname. 2. Employee with 4 fields: email, firstname, lastname, contact. 3. Front Office with 5 fields: email, firstname, lastname, airline details, vendo ...

Alignment Troubles with Icons

I am having trouble positioning some icons on the far right of my 960 grid template header, next to my logo which is on the far left. I have tried multiple ways but can't seem to get it right. Any assistance would be greatly appreciated. Below is the ...

Events are not being emitted by Socket.io

I recently started learning about socket.io and began following a tutorial on the socket.io website. I have installed everything correctly, but it seems that the socket is unable to emit the event in the index.html file. Can anyone help me with this? Here ...

The useEffect function is not being executed

Seeking assistance from anyone willing to help. Thank you in advance. While working on a project, I encountered an issue. My useEffect function is not being called as expected. Despite trying different dependencies, I have been unable to resolve the issue ...

Navigating to the next page on a dynamic component in Angular 5 by

I'm uncertain if this scenario is feasible, but I have a page that fetches a list of items from an external API. There are currently 5 elements on the page, each acting as a link to its individual dynamically generated page through query strings. For ...

convert a string to JSON format using Node.js Express

Currently, I am viewing some string data in a browser that has been processed using python-node js express. The data looks something like this: In order to manipulate the data more effectively, I would like to convert it into JSON format that follows this ...

Steps for transforming a JSON into a Class to generate objects

My JSON data is displayed below: var nodeclienthash={ socket:null, init : function() { // Initializing socket.io this.socket = new io.Socket(this.config.host, {port: this.config.port, rememberTransport: false}); } }; I am currently looking t ...

Working with conditional rendering in React Native allows us to easily change text based on different conditions. By utilizing

Hello fellow React Native beginners! I'm currently working on a feature where the text output on the screen changes based on the time of day. Specifically, I want the screen to display 'Morning' if it's morning, 'Afternoon' i ...

Implementing interactive elements such as buttons and controls on an HTML5 canvas

I've been working with the three.js 3D engine and I'm wondering how to incorporate UI buttons onto my WebGL canvas. Any ideas on how to achieve this? ...

Steps to clear the form in vue after the ajax request has been successfully submitted

Exploring Vue.js Web Form Validation with a Scenario If you are interested in the vue-form validator library, it can be found at https://github.com/fergaldoyle/vue-form For a demonstration of this scenario, check out the following jsfiddle link: https:/ ...

Having trouble with PHP SQLite3 functioning on the web server, but it works fine

I am facing an issue where my scripts are not running online on the server, despite working fine on localhost with XAMPP for testing. I have a few PHP files and a database '*.db' that I can share if needed... The scripts in PHP and SQLite are qu ...

Uncovering the Solution: Digging into a Nested ng-repeat to Access an Array in AngularJS

I am working with a recursive array in JavaScript: [{ type: 'cond', conditionId: 1, conditions: undefined }, { type: 'cond', conditionId: 2, conditions: undefined }, { type: 'group', conditionId: undefined, ...

What is the best way to display the tabcontent when clicking on a menu tab in this code, as neither method seems to work?

Take a look at my JSFiddle demo: <http://jsfiddle.net/xrtk9enc/2/> I suspect that the issue lies within the javascript section. My html code includes an Unordered List that serves as the tab menu. Each href of the menu corresponds to a tab content, ...

What is the best way to track and display the window.scrollY value in the console using Next.js

Unfortunately, my ScrollToTop component is not functioning correctly within my app. I have exhausted all possible debugging methods but am still unable to determine why the scrollY value is not being logged as expected. Even after moving the snippet to a ...

Find the item that has a specific value in its sub-property

Information Models: public class Header{ public int Identifier; public int value; public bool anotherValue; public List<Trailer> trailers; } public class Trailer{ public int ID; public Language MyLanguage; public string ...