0

I'm trying to make call a navigation bar(navbar.html) in to my index.html. Navbar.html has its own css and inside navbar.html is a script that changes the class of <li> when <a> is pressed.

I have managed to make the <li> to change highlight but when I press the <a> does not remain highlighted on the new page.

Index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    <title></title>
</head>

<body>
    <!--NAVIAGTION BAR-->
    <div id="navbar-placeholder">


    </div>


    <script>
        $(function(){
            $("#navbar-placeholder").load("Files/navbar.html");
        });
    </script>
    <!--END OF NAVIGATION BAR-->
</body></html>

navbar.html

<link rel="stylesheet" href="css/navbar.css">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>

<div class="navigation">
    <ul>
        <li class=""><a href="work.html">Work</a></li>
        <li class="active"><a href="index.html">Home</a></li>
        <li class=""><a href="contact.html">Contact</a></li>
    </ul>
</div>


<script>
    $(document).ready(function() {
        $(".navigation li").click(function() {
            $(".navigation li").removeClass("active");
            $(this).addClass("active");
        });
    });

</script>

navbar.css

.navigation{
    position: fixed;
    top: 0;
    width: 100%;
    background-color:#262126;
    text-align: center;
}

.navigation ul{
    margin: 0;
}
.navigation li{
    display: inline-block;
    padding: 15px 30px;
    margin: 10px 5px 0px 5px;
    text-decoration: none;
    font-size: 20px;
    font-family: 'Open Sans', sans-serif;
}

.navigation a{
    color: white;
    text-decoration: none;
    text-transform: capitalize;
}

.navigation li:hover{
    background-color: #F2F2F2;
    transition: 0.4s;
}

.navigation li:hover a{
    color: black;
}

.navigation li.active{
    background-color: #F2F2F2;
}
.navigation li.active a{
    color: black;
}
  • If the page get's reloaded then have a look at localStorage. – EugenSunic Sep 22 '19 at 19:54
  • 1
    You want to parse the url and then find appropriate `href` when new page loads. Easy to research how to parse the url. No point changing the class in current page when link is clicked unless it is a single page app – charlietfl Sep 22 '19 at 19:58
  • Try using the query operator `?` or the anchor `#` in the url. And then as @charlietfl said, parse the url. – Mouser Sep 22 '19 at 20:02

1 Answers1

1

The logic is backwards. Adding the class when click occurs is pointless since you are immediately leaving that page

When each page loads match the current location.href to the links and add class then.

var $navItems = $(".navigation li").removeClass("active"); 

$navItems.filter(function(){
  return $(this).find('a').prop('href') === location.href;
}).addClass("active");
charlietfl
  • 170,828
  • 13
  • 121
  • 150