View Full Version : reference Javascript function within a div

01-29-2009, 09:07 PM
My AJAX call places the following HTML into the innerHTML of a <DIV>. The problem is the javascript within it doesn't work. If I manually code the same HTML into a DIV it works.

<SCRIPT language=JavaScript>
function pMenu()
<DIV id=pMenuDiv onmouseover=pMenu()>The Div</DIV>

By populating innerHTML, I don't think the DOM knows this script exists. How do I make it exist? I believe other posts have dealt with this issue but the solution is wrapped in other "canned" scripts that I'm struggling to understand......

01-30-2009, 02:00 PM
The method you've described won't work. Rather if you try to embed the JS code through innerHTML it is not going to work.

Instead you can add the JS files through DOM based methods. An example would be the following:

function loadScript(){
var script = document.createElement('script');
script.type = "text/javascript";
script.src = "your_script_file_name.js"; //Mention the correct path for your requirement

Note that I am inserting the script element as the last child of the body element.

The script file that you dynamically insert can have certain function calls in it and it will be triggered as soon as the insertion is over.

Hope this helps.

01-30-2009, 02:32 PM
Thanks for your suggestion. Some questions:
1.) Does your solution imply that there is some a convention established for the data returned by the AJAX call?
2.) Does your solution only work if the script is in a JS file or could it work for my example?
3.) If I don't know what I'm going to get back from the AJAX call can I still make it work?

Last night I found greybox at orangoo.com it seems like maybe they have this figured out?