Search code examples
javascriptjqueryhtmlparentonload

Is there a way to load a function from the htm that you're loading with .load()? JQuery


In my main window main.htm I have a div button that loads another htm file into a large div when clicked. I use .load() to achieve this:

 $('#mainpanel').load("search.htm");

There is a function in "search.htm" called test() which only consists of alert("hi"); and I want this to load when search.htm is loaded into the div. I used the body onload tag and window.onload = test; and even $( document ).ready() but nothing works. It only works if I access search.htm on its own, but if I access it through main.htm it does't alert "hi". Is there a way to use .load() to load the page and a function? or is there a way to get the function the onload when I select the div that loads the page?


Solution

  • The onload / document ready will only fire once (when the parent document is loaded)

    Either add a

    <script type="text/javascript">
        test();
    </script>
    

    to the end of the search.htm (so it's executed after everything else in the page has been parsed) or call test(); from the parent page after the load completes (via a callback)...

    $('#mainpanel').load("search.htm", function(){
        test();
    });
    

    It depends which page you want to be responsible for executing the function. In the latter case, the parent page needs to know the name of the function in search which may or may not fit your design.