safari ReferenceError: Can't find variable

18,587

Javascript that is added dynamically to a page needs to be eval-d in order to correctly initialise.

In order for that to work correctly for function definitions they need to be formatted slightly differently. eg:

<script>
newfunc = function()
{
alert("here");
}
</script>
<button type="button" onclick="newfunc()">Press me</button>

After adding the content to the DIV, extract all tag elements from the DIV and eval their contents.

For example, using PrototypeJS (http://www.prototypejs.org/api/):

$(divid).innerHTML.evalScripts();

Where divid is the ID of the div you just populated with content.

Share:
18,587
adam
Author by

adam

Updated on June 05, 2022

Comments

  • adam
    adam almost 2 years

    I have the following in its own DIV

    <script>
    function newfunc()
    {
    alert("here");
    }
    </script>
    <button type="button" onclick="newfunc()">Press me</button>
    

    On IE and FF it works fine, but on Safari (at least Safari 4.0.5) it says “ReferenceError can't find variable” - now the content was loaded into the DIV dynamically and it seems Safari can't see the function definitions within this DIV - however, if I put the function newfunc() onto the main HTML page (i.e. not in the DIV) then the button press does call the function.

    It’s as if Safari doesn't see the Javascript functions that have been added to the DIV.

    Any help would be appreciated.

    adam