David
David

Reputation: 143

Add/Remove classes if specified class exists on different element

On my site, I am trying to achieve a fadeInUp effect for my sub-menu when I hover over the menu items in my navbar and a fadeOutDown effect when the mouse leaves from hovering over the menu item (like on this site). I already have the animations set up and I have written some Javascript that's gotten me a little bit closer to my desired result, but the logic behind it is wrong, so it's all buggy. This is my current Javascript code:

$(document).ready(function () {
    $('ul.elementor-nav-menu li.menu-item a').hover(
      function () {
        $('ul.sub-menu').removeClass('animated fadeOutDownSmall');
        $('ul.sub-menu').addClass('animated fadeInUpSmall');
      },
      function () {
        $('ul.sub-menu').removeClass('animated fadeInUpSmall');
        $('ul.sub-menu').addClass('animated fadeOutDownSmall');
      }
    );
  });

So basically, when I hover over the menu item, it adds the "fadeInUpSmall" class to the ul element that has the class "sub-menu" and when my mouse leaves from hovering over the menu item, it removes the class "fadeInUpSmall" and adds the class "fadeOutDownSmall". You can see how that wouldn't work, as if I move my mouse to navigate the submenu/megamenu, they start glitching out, fading in and back out etc. However, when I hover over a menu item that has a sub-menu, you can see in inspect element that the class "highlighted" gets added to the respective 'a' tag. So, my question is, how can the Javascript code that I provided be modified so that it finds if the class "highlighted" exists on the 'a' element and adds/removes the fadeInUpSmall and fadeOutDownSmall classes respectively?

Upvotes: 0

Views: 791

Answers (1)

Aaron Tomlinson
Aaron Tomlinson

Reputation: 285

Mouse enter and mouse leave.
MouseEnter
Jquery
Javascript
Has Class
Jquery

$('ul.elementor-nav-menu li.menu-item a').addEventListener('mouseenter', (e) => {'
  if($( "#mydiv" ).hasClass( "foo" )){
    $('ul.sub-menu').removeClass('animated fadeOutDownSmall')
    $('ul.sub-menu').addClass('animated fadeInUpSmall')
  }
})

$('ul.elementor-nav-menu li.menu-item a').addEventListener('mouseleave', (e) => {
  $('ul.sub-menu').removeClass('animated fadeInUpSmall')
  $('ul.sub-menu').addClass('animated fadeOutDownSmall')
})

It may need to be used vice versa, depends on how you want to use it.

CSS could work like this.

.dropdown{
  height:0%;
  opacity:0;
  transition: height 0.3s ease-out, opacity 0.3s ease 0.5s;
}
.dropdown.active:hover {
  height:100%;
  opacity:1
}

Upvotes: 1

Related Questions