I'm trying to use jquery to initialize the active class for a navigation menu when loading it as a separate html file.
I am not familiar with PHP and I'm pretty new to website generation, so I'm not very comfortable with JS and the integration between the usual languages (HTML, CSS, and JS). I've searched throughout Stack Overflow and tried a couple of solutions but I am clearly missing something:
- Navbar active class resets on page load
- JQuery Active Class Error when page is not in navbar
- Bootstrap navbar active class
- Jquery Active page link
I think my problem has to do with waiting on the page to load. I implemented an "on click" function that works, but when I actually load a page in the menu, it does set the class to active in <li>
.
EDIT: To clarify, I successfully set the active class with the click event, the background will change to blue. However, when the link for the menu is actually activated, the background flashes blue and then reloads as black. I am trying to figure out how to set the active class when the navigation menu is being called through Jquery. To prove my style is working on a click event, please see the screenshot here.
Here is a simplified version of what I have right now:
index.html
<!DOCTYPE html>
<html>
<head>
<link href="style.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.7.2.min.js" type="text/javascript"></script>
</head>
<body>
<div class="container">
<!--Navigation bar-->
<div id="nav-placeholder"></div>
<script>
$("#nav-placeholder").load("nav.html");
</script>
<!--end of Navigation bar-->
<div class="mainBlock">
<div class="mainPage">
<div class="mainContent">
<p>Welcome! This is my website.</p>
</div>
</div>
</div>
</div>
</body>
</html>
nav.html
<!DOCTYPE html>
<html>
<div class="navbar">
<ul>
<li><a href="/index.html" id="navHome">Home</a></li>
<li><a href="/ref.html" id="navRef">References</a></li>
</ul>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).on("click", "ul li", function(){
$('.navbar li').removeClass('active');
$(this).addClass("active");
})
</script>
// Inserted scripts here based on other stackoverflow posts
</div>
</html>
style.css
.navbar {
width: 1000px;
background: #000;
text-align: left;
}
.navbar ul {
margin: 0px;
padding: 0px;
}
.navbar ul li {
list-style-type: none;
display: inline-block;
padding: 5px 10px;
color: #fff;
text-decoration: none;
border-right: 1px solid #fff;
}
.navbar ul li .active{
background: #33b;
}
.navbar ul li a:hover {
border-bottom:3px #FFF solid;
}
.navbar a:link {
color: #fff;
text-decoration: none;
}
.navbar a:visited {
color: #fff;
text-decoration: none;
}
I expected to get a blue highlight for the current item in the navigation menu. When clicked on but not selected (i.e. page does not actually load), this is successfully set to the active class (background is blue).