0

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?

2
  • 4
    You can pass a callback function to .load() and that function will be called when the content has been added to the DOM. Commented May 10, 2017 at 20:15
  • thanks for the help! Commented May 10, 2017 at 20:22

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.