How set default display none when mouse over is outside its parent element JavaScript

How set default display none when mouse over is outside its parent element JavaScript
0

#1

When someone’s mouse cursor is outside its parent element (<div id="side-nav" class="sidebar-navigation" data-attribute="sidebar">. All the tabs should be set to display none, but now there is always one tab that is being set to display block. Could anyone here help me to solve this problem. Maybe I should rewrite this code, but need some guidance. And most importantly it should be done in pure JS and no CSS please!


#2

Replace mouseover event with combination of mouseenter and mouseout ?

(function() {
    "use strict";
    const sideNav = document.getElementById('side-nav');
    const navTab = sideNav.querySelectorAll('.nav-tab');
   
    navTab.forEach(tab => {
        tab.addEventListener('mouseenter', function(e) {
            e.preventDefault();

            const nodes = Array.from(e.target.parentNode.querySelectorAll('.nav-tab-sub-category'));
            nodes.forEach(nodes => nodes.style.display = "none"); 
            if(e.target.nextElementSibling) {
                e.target.nextElementSibling.style.display = "block";                
            }
        });
        tab.addEventListener('mouseout', function(e) {
            e.preventDefault();
            const nodes = Array.from(e.target.parentNode.querySelectorAll('.nav-tab-sub-category'));
            nodes.forEach(nodes => nodes.style.display = "none"); 
        }); 
    });   
})();
 

Additionally, you need to correctly close div for Women's Clothing It should look like

<div class="nav-tab" data-attribute="product_a">Women's Clothing</div>
  <div class="nav-tab-sub-category">
  <div>Women's Clothing</div>
  <div>Women's Clothing</div>
  <div>Women's Clothing</div>
  <div>Women's Clothing</div>
  <div>Women's Clothing</div>
  <div>Women's Clothing</div>
</div>

#3

Problem of adityaparab’s solution above is that the display block would not be set when someone hovers over a specific tab and go to that expanded tab from there.


#4

Maybe you could instead set the sub-categories to disappear when leaving the whole side-bar?

 sideNav.addEventListener('mouseleave', function(e) {
     e.preventDefault();
     const nodes = Array.from(e.target.querySelectorAll('.nav-tab-sub-category'));
     nodes.forEach(nodes => nodes.style.display = "none"); 
 }); 

#5

Great! You are the first who could solve this function :stuck_out_tongue: Thanks a lot.