Home > Enterprise >  Show current page on the menu Jquery
Show current page on the menu Jquery

Time:05-14

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 >
    <ul id="nav">
        <li><a id="homeLink" href="index.html">home</a></li>
        <li><a id="pessoal"  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.

CodePudding user response:

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");
})

CodePudding user response:

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 >
    <ul id="nav">
        <li><a id="homeLink" href="index.html">home</a></li>
        <li><a id="pessoal"  href="pessoal.html">pessoal</a></li>
        <li><a id="galeria" href="galeria.html">galeria</a></li>
    </ul>
</div>

  • Related