0

I have one script 'script.js' set up to assign active class to an li tag based on the url.

window.onload = function () {
jQuery(document).ready(function ($) {
    // Get current path and find target link
    var path = window.location.pathname.split("/").pop();

    // Account for home page with empty path
    if (path == '') {
        path = 'HomePage.html';
    }

    var target = $('nav a[href="' + path + '"]');
    // Add active class to target link
    target.addClass('active');
});

Second script called 'JavaScript.js' this adds in the html of my shared menu bar from a separate html file:

window.onload = function () {var xmlhttp; var oe = document.getElementById("nav");xmlhttp = new XMLHttpRequest();xmlhttp.open("GET", "SharedMenu.html", false);xmlhttp.send();oe.innerHTML = xmlhttp.responseText;};

How do I make them work together in this format:

<!DOCTYPE html>
<html>
<head>
<title>jQuery Active Class</title>
<link href="style.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<script src="script.js"></script>
<script src="JavaScript.js"></script>

</head>
<body>

<nav id="nav">
</nav>

<h1>contact</h1>
</body>
</html>
3
  • Why don't you add both of those scripts into one file? Commented Nov 14, 2020 at 7:45
  • 1
    You are looking for 'nav' wich is not ready yet, just put your JavaScript.js before the closure of the body. Also the idea of @HarshanaSerasinghe is a good one, will post an answer for you with that solution. Commented Nov 14, 2020 at 7:47
  • I have already tried both those ways and it hasn't worked Commented Nov 14, 2020 at 7:54

1 Answer 1

2

Here is a single script to use.

$(function(){
    //Load the SharedMenu.html
    $.get("SharedMenu.html",function(html){
        //ON LOADED
        // Create the menu
        $('#nav').html(html);
        // Get current path and find target link
        var path = window.location.pathname.split("/").pop();

        // Account for home page with empty path
        if (path == '') path = 'HomePage.html';

        //add the class
        $('#nav a[href="' + path + '"]').addClass('active');
    });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.