noclist
noclist

Reputation: 1819

How to manipulate html from a jQuery load() with javascript

I am loading an HTML file into another HTML file using the jQuery load() method:

$("#sidebar").load("templates/sidebar.html");

<div id="sidebar"></div>

I have some javascript I would like to run on the loaded HTML file. This script isn't working, I believe due to the fact that it is unable to see the new HTML at the time of it's execution. For example, this line of jQuery would be unable to see my class of menu that exists within sidebar.html.

$('.menu').css('left', '100');

Is there any way I can force the script to wait until my loaded HTML is rendered before executing?

Upvotes: 0

Views: 501

Answers (1)

jsmith
jsmith

Reputation: 976

You can pass a function as an additional parameter to the .load() call and it will be executed at the end of the .load() call after the new elements are added into the DOM

$("#sidebar").load("templates/sidebar.html", function () { 
    $('.menu').css('left', '100');
});

<div id="sidebar"></div>

Upvotes: 2

Related Questions