Search code examples
javascripthtmlajaxfunctioninnerhtml

Run custom javascript from dynamicaly loaded innerHTML context


I have an HTML document

...

<div id="test"></div>

...

Then i dynamicaly load some context to #test div.

function change()
{
ws = document.getElementById(id);
str = '<script>function ttest(){window.alert("Yahoo!!!")}</script><select><option onclick="ttest();">1</option><option >2</option></select>';
ws.innerHTML = str;
}

window.onload = change();

When the page is loaded a custom script

<script>function ttest(){window.alert("Yahoo!!!")}</script>

doesnt work.

It works perfect when its put static without any innerHTML. Also it works when its not a custom function.

How can i make my custom function work, when it was loaded dynamically using innerHTML or/and AJAX+innerHTML ?


Solution

  • Add your script to the document.head via createElement. So something like this:

    var script = document.createElement("script");
    script.innerHTML = "function ttest() { alert('Yahoo'); }";
    document.head.appendChild(script)