2

I'm currently building a website and trying to get this issue to work.

I have my header in a separate HTML document which looks like this:

<div class="topnav" id="myTopnav">
<a href="Index.html" id="home"><i class="fa fa-fw fa-home"></i>Home</a>                  
<a href="Drinks.html" id="drinks"><i class="fa fa-fw fa-coffee"></i>Drinks</a>
</div>

Now on every page I load the header from this HTML:

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){ 
$('#content').load("Header.html");
});
</script>
</head>

<header class="head">
<div id="content"></div>
</header>

Now I'm trying to add dynamically a class to the "a href"-Tag to make it active but this does not work. I tried to write another function in the "head"-Tag:

 <script>
 function addAct() {
 var element = document.getElementById("#home");
 element.classList.add(".active");
 };
 </script>

and call it manually in the "head"-Tag right after calling the loading function:

 <script>addAct()</script>

This does not seem to work. I tried a lot of other solution but could not find anything that is working. Can someone help?

Thanks a lot!

1
  • I see typo in your code first this #home should not have # simply write document.getElementById("home"); a Commented Aug 21, 2020 at 14:09

2 Answers 2

2

Did you try use complete callback in .load()

like this:

$(document).ready(function(){ 
    $('#content').load("Header.html", function(){
       // complete loading
       $('#home').addClass('active')
    });
});

If you use native js you don't need set dot (.) in classList.add('active') if you add dot you will get <div class=".active"></div>

Sign up to request clarification or add additional context in comments.

1 Comment

Worked great. Thanks a lot! Did not have the idea to call the function in the code itself.
0

The .load() method is asynchronous. Hence you need to take advantage of the complete callback (i.e.: only when you have the data you can apply the class).

Moreover you have some mistakes:

  1. change from document.getElementById("#home") to document.getElementById("home")

  2. change from element.classList.add(".active"); to element.classList.add("active");

The code:

$('#content').load("https://gist.githubusercontent.com/gaetanoma/7b7ad4592c2b69e14b7cbe0c888ef1be/raw/3cbf59473c5f55a1db5a29f51498f3e9d6739e9b/Header.html", function() {
    var element = document.getElementById("home");
    element.classList.add("active");
});
.active {
    background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

<header class="head">
    <div id="content"></div>
</header>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.