Home > Back-end >  Applying class to only the active nav item, workaround for bootstrap
Applying class to only the active nav item, workaround for bootstrap

Time:06-23

I'm working on a site where I'm using bootstrap, but I'm actually trying to apply a custom style to active nav items (more of a backdrop rather than just text color)

However, in order to get started and test things I'm just using the white text color to get it working and I have no luck so far.

I've included the JS, but basically I'm trying to apply a class to the span tag within the nav item (li) link (a) for any active item.

What exactly am I doing wrong here? I've applied an empty span to each line item link which is where I want the class to go for the active item

$(document).ready(function () {
    $('ul.navbar-nav > li.nav-item > a.nav-link')
            .click(function (e) {
        $('ul.navbar-nav > li.nav-item > a.nav-link > span')
            .removeClass('active-pill');
        $(this).addClass('active-pill');
    });
});
a.active-pill{
    color: white;
}
.nav-link{
    color:black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"
        integrity="sha384-xrRywqdh3PHs8keKZN 8zzc5TX0GRTLCcmivcbNJWm2rs5C8PRhcEn3czEjhAO9o"
        crossorigin="anonymous"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"
          integrity="sha384-ggOyR0iXCbMQv3Xipma34MD dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">    
        
<ul >
    <li >
        <a  href="#"><span >Home</span>
        </a>
    </li>
    <li >
        <a  href="#"><span>Contact</span></a>
    </li>
    <li >
        <a  href="#"><span>FAQs</span></a>
    </li>
</ul>

CodePudding user response:

I think if you just make the selector more specific it should work.

a.active-pill{color: white}

Bases on running it locally it seems that the color from the .nav-link takes priority so being for specific will fix that.

CodePudding user response:

It seems that you issue is when things get loaded. so maybe try using this:

window.onload = function() {
  $('ul.navbar-nav > li.nav-item > a.nav-link')
            .click(function (e) {
        $('ul.navbar-nav > li.nav-item > a.nav-link > span')
            .removeClass('active-pill');
        $(this).addClass('active-pill');
    });
};

window.onload happens later after everything is loaded and might solve the issue

  • Related