From the linked (below) post

"Iif you are adding your navbar as an include (following DRY principles), here is a nice clean way to not only automatically enable the active item in the navbar and its submenu, but also append the (current) for screenreaders, to the appropriate link text. See link for full technique. Enable the active item in the navbar and its submenu, as well as append the active "sr-only" current tag for screen readers. 

jQuery code:


( function ($) {
    var activenav,
        matches = document.body.className.match(/(^|\s)page-(\w+)(\s|$)/); //
    if (matches) {
        activenav = matches[2]; 
        $(".navbar-nav .nav-item").each( function () {
            if( $(this).hasClass(activenav) ) {
                $(this).addClass('active')
                       .find(".nav-link").append(" (current)>");
            }
        });
        $(".navbar-nav .dropdown-item").each( function () {
            if( $(this).hasClass(activenav) ) {
                $(this).addClass('active')
                       .append(" (current)>");
            }
        });
    }
 
})

Source: https://blog.madhousegraphics.com/2017/08/setting-the-active-navbar-item-with-bootstrap-4-and-jquery/

Enable the active item in the navbar and its submenu, as well as append the active "sr-only" current tag for screen readers. 
joeruggeri.com joeruggeri.com :: posts

Setting the Active Navbar item with Bootstrap 4 and jQuery

Web Tech | Nov. 23, 2019

From the linked (below) post

"Iif you are adding your navbar as an include (following DRY principles), here is a nice clean way to not only automatically enable the active item in the navbar and its submenu, but also append the (current) for screenreaders, to the appropriate link text. See link for full technique. Enable the active item in the navbar and its submenu, as well as append the active "sr-only" current tag for screen readers. 

jQuery code:


( function ($) {
    var activenav,
        matches = document.body.className.match(/(^|\s)page-(\w+)(\s|$)/); //
    if (matches) {
        activenav = matches[2]; 
        $(".navbar-nav .nav-item").each( function () {
            if( $(this).hasClass(activenav) ) {
                $(this).addClass('active')
                       .find(".nav-link").append(" (current)>");
            }
        });
        $(".navbar-nav .dropdown-item").each( function () {
            if( $(this).hasClass(activenav) ) {
                $(this).addClass('active')
                       .append(" (current)>");
            }
        });
    }
 
})

Source: https://blog.madhousegraphics.com/2017/08/setting-the-active-navbar-item-with-bootstrap-4-and-jquery/

Other posts tagged with Javascript