'Show current page on the menu Jquery
I'd like to change the background color of the current page the user is on. I've tried some code but they don't work. My js code is in a different file and it's loading the menu to some of the pages.
$(function(){
$("#menu-nav").load("menu.html");
$("#footer").load("footer.html");
})
/* The menu code is in another file */
<div class="menu-nav">
<ul id="nav">
<li><a id="homeLink" href="index.html">home</a></li>
<li><a id="pessoal" class="a-borda" href="pessoal.html">pessoal</a></li>
<li><a id="galeria" href="galeria.html">galeria</a></li>
</ul>
</div>
The code I've tried, but the class is not added
var section = window.location.pathname;
if (section == "/index.html"){$("#homeLink").attr("class", "active");}
CSS:
.active {
background-color: red;
}
also tried with .addClass( className ), but doesn't add the class. I don't know if the fact I'm bringing the files with Jquery it's interfering in the process or if I'm using the wrong syntax.
Solution 1:[1]
You can add a class dynamically depending on the page
$(document).ready(function() {
let section = window.location.pathname.substring(1);
$(`a[href='${section}']`).addClass("active");
})
Solution 2:[2]
You need to wrap your var section = window.location.pathname; ... if (section == "/index.html"){$("#homeLink").attr("class", "active");}
into a $(function(){
. This lets the script wait until the DOM finishes loading.
$(function(){
var section = window.location.pathname;
//Changed the section to /js as the script is run from https://stacksnippets.net/js
if (section == "/js") {
$("#homeLink").addClass("active");
}
})
.active {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="menu-nav">
<ul id="nav">
<li><a id="homeLink" href="index.html">home</a></li>
<li><a id="pessoal" class="a-borda" href="pessoal.html">pessoal</a></li>
<li><a id="galeria" href="galeria.html">galeria</a></li>
</ul>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Marcin M?sior |
Solution 2 | Tom Groot |