2

I have a shared left menu in a separate file from my pages so that I can update it in one place.

I am loading it onto the page in a .js file like so:

$(function () {
    $("#left-nav").load("templates/left-nav.html", function() {
        ...
    });

    ...
}

I would like to be able to set the nav-list item for the page to be selected. Something like this:

$("#calendar").addClass("selected");

...where #calendar is the ID of a list item in my left-nav.html template file.

Everything I've read says that I have to call addClass as a callback after I load in the file, but the following doesn't seem to work:

$(function () {
    $("#left-nav").load("templates/left-nav.html", function() {
        $("#calendar").addClass("selected");
    });

    ...
}

Question: Is it possible to add classes to dynamically added content on a page, and if so, how should I do it? Thanks!

Huangism
  • 16,278
  • 7
  • 48
  • 74
Jon
  • 3,154
  • 13
  • 53
  • 96
  • 1
    Are you sure the results have an element with the ID of `calendar`? In your text you say the id is `#calendar` I just want to confirm that that's a typo and that you meant the query is `#calendar` and the ID is `calendar` – Shriike Nov 12 '14 at 20:56
  • After you load the template, in the console, what does `$('#calendar').length` output? – Tomanow Nov 12 '14 at 20:59
  • Can you post `templates/left-nav.html` HTML? – dfsq Nov 12 '14 at 20:59
  • The `load()` callback is fired immediately after the request succeeds, and not necessarily after the content loads. Consider using `get()` and a `complete` function. http://api.jquery.com/jquery.get – isherwood Nov 12 '14 at 21:01
  • God bless America. @Shriike caught my error. That fixed it -- Thanks! – Jon Nov 12 '14 at 21:02

1 Answers1

1

The code is correct as written, adduming that left-nav.html does contain an element with the ID of calendar.

The completed event is fired after the HTML is added to the DOM according to the jQuery documentation.

Shriike
  • 1,351
  • 9
  • 20