Bassie Bassie - 1 year ago 72
HTML Question

How to Ensure Elements have Loaded Before Adding Class on PageLoad

I have the following bit of code, which first loads a navbar to the website on page load (this is so that I don't have to create a new navbar for each page):

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

<script>$( "#nav" ).load( "nav.html" );</script>

And to show the "active" tab for that page, I have the following script:

window.onload = function() {
document.getElementById('lindex').className = 'active';

However, when the page loads, I am seeing this error in the console (for the

index.html:70 Uncaught TypeError: Cannot set property 'className' of null

And the "active" tab does not update when I navigate to the page. Strangely, it does seem to add the class when I reload the page, but intermittently. Does anyone know why this might be happening?

Here is the code for the navbar (nav.html):

<nav class="navbar navbar-inverse ">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>

<a href="#" class="navbar-left navbar-logo"><img src="/img/logo.png"></a>

<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li id="lindex" class="listitem"><a href="index.html">Home</a></li>
<li id="lpandp" class="listitem"><a href="productsandpurchasing.html">Products & Purchasing</a></li>
<li><a href="#about">Freight & Distribution</a></li>
<li><a href="#about">Blog</a></li>
<li><a href="#contact">Contact Us</a></li>
<li class="dropdown">

I have also tried:

$(function() {

But this doesn't seem to work either, unless I refresh the page after navigating to it.

Answer Source

Try the following

<script>$( "#nav" ).load( "nav.html",function(){
  $('#lindex').addClass('active');// add the class after the nav is loaded
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download