dungey_140 dungey_140 - 1 month ago 7
jQuery Question

hasClass + addClass not functioning

The below script is supposed to add a class (.active) to .global-header if .navigation.primary has a class of .active, but it doesn't seem to be working?

JS

if($(".navigation.primary").hasClass("active")) {
$('.global-header').addClass('active');
}


HTML

<header class="global-header">
<div class="site-navigation">
<div class="left-menu"></div>
<div class="right-menu"></div>
</div>
</header>

<nav class="navigation primary">Menu</nav>

Answer

Based on the comments, when you load the page, if the element with navigation.primary has no active class, but later, when an action happens will get the active then you need to add the event listener around your code to that event what triggers the class addition.

If the navigation.primary has the active when page loads, you need to add document ready:

$(function() { //when document is ready
    if($(".navigation.primary").hasClass("active")) {
       $('.global-header').addClass('active');
    }
});

or if an event happens, for example scroll the window:

$(function() { //when document is ready
   $(window).on('scroll', function() { //When scrolling
        if($(".navigation.primary").hasClass("active")) {
            $('.global-header').addClass('active');
        }
   });
});