I am working on a project where I want to dynamically change the menu color based on the page being loaded. Since this is an HTML project, I cannot use server-side languages for this. Instead, I decided to retrieve the name of the HTML file being loaded and adjust the menu color accordingly. However, I encountered a strange issue with this approach. Let me elaborate.
My Menu :
<nav>
<ul>
<li><a class="menu-option" id="about" href="about.html">About</a></li>
<li><a class="menu-option" id="trainer" href="#">Trainer / Consultant</a></li>
<li><a class="menu-option" id="testimonial" href="#">Testimonials</a></li>
<li><a class="menu-option" id="programs" href="#">Programs</a></li>
<li><a class="menu-option" id="contact" href="#">Contact us</a></li>
</ul>
</nav>
The JS
$(document).ready(function() {
$("header").load("includes/header.html");
$("footer").load("includes/footer.html");
var page = location.pathname.split("/").slice(-1);
switch (page[0])
{
case "about.html":
$(".menu-option").css('color', 'white');
$("#about").css('color', '#E45C02');
break;
case "trainer.html":
$(".menu-option").css('color', 'white');
$("#trainer").css('color', '#E45C02');
break;
case "programs.html":
$(".menu-option").css('color', 'white');
$("#programs").css('color', '#E45C02');
break;
case "testimonial.html":
$(".menu-option").css('color', 'white');
$("#testimonial").css('color', '#E45C02');
break;
case "contact.html":
$(".menu-option").css('color', 'white');
$("#contact").css('color', '#E45C02');
default:
$(".menu-option").css('color', 'white');
break;
}
});
While inspecting with Firebug, I noticed that the case was being invoked but the color of "About" was not changing. To troubleshoot, I added an alert in the "about" case:
case "about.html":
alert("about");
$(".menu-option").css('color', 'white');
$("#about").css('color', '#E45C02');
break;
Surprisingly, adding the alert made it work as expected. I am puzzled about why the code fails without the alert statement. What purpose does it serve? What am I overlooking here? Do I need to add a timeout function?
I also attempted enclosing the switch case inside a jQuery ready function for the header:
$("header").ready(function(){
// Switch case here
// Still no luck !
});