RichardDev
RichardDev

Reputation: 552

Add/Remove classes from navigation loaded with Jquery

I am loading in the content of my sidebar navigation with jquery from a nav-content.html file so I don't have to update it on every page each time it updates.

What I am trying to do is when on a specific page, the sidebar nav with uncollapse based on what category that page is on.

I am trying to target elements in that loaded nav to be active when on certain pages and it only works when the nav is hard coded into the page's html but it doesn't work when I load it in from the nav-content.html file with jquery.

I did noticed when i view the source code on browser it doesn't actually paste in the html but still displays it which I think is the disconnect but I am not 100%. Not sure if I should look into different way to load it in or if my jquery is the issue.

Any insight would be greatly appreciated.

HTML:

<nav>
 <div id="sidebar">
  <div id="sidebar-content">
      <!-- nav loads here from nav-content.html -->
  </div>
 </div>
</nav>

Jquery:

/*Loads the Nav */`
window.onload = function(){
    $.get("nav-content.html", function(data){
        $("#sidebar-content").html(data);
    })
  }
/* changes classes within the loaded nav based on what page it's on */
$(document).ready(function() {
  $('ul#devSubmenu').removeClass('collapse'),
  $('ul#appStackSubmenu').removeClass('collapse'),
  $('a[href^="#devSubmenu"]').attr("aria-expanded","true"),
  $('a[href^="#appStackSubmenu"]').attr("aria-expanded","true");
 });

I asked this a few days ago but this is a rephrased/re-explained of deleted post.

Upvotes: 1

Views: 77

Answers (1)

Ed Lucas
Ed Lucas

Reputation: 7305

Two things to get you on the right path.

1) jQuery's get() does not load an HTML file. You might mean to use load() to get your sidebar content: https://api.jquery.com/load/

2) $(document).ready fires before window.onload. See: window.onload vs $(document).ready()

In order to ensure that your content is loaded before modifying the classes, you can make your modifications in the callback from load() (the function passed as the second parameter to load()).

Something like [untested]:

$(function() {
  $( "#sidebar-content" ).load( "nav-content.html", function() {
    $('ul#devSubmenu').removeClass('collapse'),
    $('ul#appStackSubmenu').removeClass('collapse'),
    $('a[href^="#devSubmenu"]').attr("aria-expanded","true"),
    $('a[href^="#appStackSubmenu"]').attr("aria-expanded","true");
  });
});

The wrapping $(function() { ... }) is just jQuery shorthand for $(document).ready();

Upvotes: 1

Related Questions