Bassie
Bassie

Reputation: 10390

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:

<script>
    window.onload = function() {
        document.getElementById('lindex').className = 'active';
    };
</script>

However, when the page loads, I am seeing this error in the console (for the document.getElementById line):

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>
      </button>

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

    </div>
    <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">
        </li>
      </ul>
    </div>
  </div>
</nav>

I have also tried:

$(function() {
  $('#about').addClass('expand');
});

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

Upvotes: 0

Views: 1107

Answers (3)

Anju
Anju

Reputation: 39

$("#lindex").addClass("Your Class Name");

Upvotes: 0

Mowgli
Mowgli

Reputation: 129

       $( document ).ready(function() {
            console.log( "ready!" );
             $( "#nav" ).load( "nav.html");
             console.log( "after load nav.html!" );
                     //add the class here 
             $('#lindex').addClass('active');

        });

Upvotes: 0

madalinivascu
madalinivascu

Reputation: 32354

Try the following

<script>$( "#nav" ).load( "nav.html",function(){
  $('#lindex').addClass('active');// add the class after the nav is loaded
});</script>

Upvotes: 1

Related Questions