safari ReferenceError: Can't find variable

adam picture adam · Dec 8, 2010 · Viewed 18k times · Source

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

Answer

ndtreviv picture ndtreviv · Jan 5, 2012

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.