Advanced Search

Results 1 to 3 of 3

Thread: reference Javascript function within a div

  1. #1
    Join Date
    Jan 2009
    Posts
    2
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default reference Javascript function within a div

    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.

    <html>
    <body>
    <SCRIPT language=JavaScript>
    function pMenu()
    {
    alert("duh");
    }
    </SCRIPT>
    <DIV id=pMenuDiv onmouseover=pMenu()>The Div</DIV>
    </body>
    </html>

    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......
    Last edited by keenanstahl; 01-30-2009 at 01:17 PM. Reason: Trying to clarify my problem.

  2. #2
    Join Date
    Sep 2005
    Location
    India
    Posts
    1,626
    Thanks
    6
    Thanked 107 Times in 107 Posts

    Default

    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:

    Code:
    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
    	document.body.appendChild(script);
    }
    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.

  3. The Following User Says Thank You to codeexploiter For This Useful Post:

    keenanstahl (01-30-2009)

  4. #3
    Join Date
    Jan 2009
    Posts
    2
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default

    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?

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •