Question

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?

Was it helpful?

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.

OTHER TIPS

Using window.onload or $( document ).ready() doesn't make sense because the document is most likely already loaded when you run that function.

You can pass a callback to .load and access the function inside there. The callback is executed when the other page is loaded:

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

Of course test must be in global scope for this to work.


As always, it's advisable to the read the documentation of the methods you are using: https://api.jquery.com/load/.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top