"Active Menu on Page Load"
Bootstrap 4.1.1 Snippet by RizwanAkram

<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <!------ Include the above in your HEAD tag ----------> <ul class='menu'> <li><a href="index.html">Home</a></li> <li><a href="javascript.html">JavaScript</a> <ul class='submenu'> <li><a href="angular.html">AngularJS</a></li> <li><a href="jquery.html">jQuery</a></li> <li><a href="react.html">React JS</a></li> </ul> </li> <li><a href="blog.html">Blog</a></li> </ul>
/* Menu */ .menu { list-style-type: none; margin: 0; padding: 0; overflow: hidden; background-color: darkturquoise; } .menu li { float: left; } .menu li a { display: block; color: white; text-align: center; padding: 14px 16px; text-decoration: none; } .menu li ul{ display: none; } .menu li a:hover { background-color: #2b90f5; } .active{ background: #2b90f5; } /* sub menu */ .submenu{ position: absolute; list-style: none; color: black; background-color: #f9f9f9; min-width: 160px; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); padding-left: 0; } .submenu li{ width: 100%; float: none; } .submenu li a{ color: black; } .submenu li a:hover{ background-color: #ddd; } .menu li:hover .submenu{ display: block; } .subactive{ background: #ddd; }
$(document).ready(function() { // Get current page URL var url = window.location.href; // remove # from URL url = url.substring(0, (url.indexOf("#") == -1) ? url.length : url.indexOf("#")); // remove parameters from URL url = url.substring(0, (url.indexOf("?") == -1) ? url.length : url.indexOf("?")); // select file name url = url.substr(url.lastIndexOf("/") + 1); // If file name not avilable if (url == '') { url = 'index.html'; } // Loop all menu items $('.menu li').each(function() { // select href var href = $(this).find('a').attr('href'); // Check filename if (url == href) { // Select parent class var parentClass = $(this).parent('ul').attr('class'); if (parentClass == 'submenu') { // Add class $(this).addClass('subactive'); $(this).parents('.menu li').addClass('active'); } else { // Add class $(this).addClass('active'); } } }); });

Related: See More


Questions / Comments: