1

I dinamically add divs with onlick event, but clicking got an error (Mozilla Firefox): "ReferenceError: myfoo is not defined". If I change onclick event to alert, it works fine, but non with mysefl written functions.

Here is jsfiddle

http://jsfiddle.net/UJ85S/5/

function myfoo(x)
{
    alert(x);
}

$("#some").html('<div id="cool_div" onclick="myfoo('+"'xwe'"+');"></div>');

Can you, please, explain what is wrong? (I understant that can assign.click event, but is it possible through onclick?).

Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
Tigran
  • 1,049
  • 3
  • 15
  • 31

2 Answers2

3

What you really need to do is not let jsFiddle wrap it inside the onload event as this uses a function which creates new scope. Your function is then not accessible outside this new scope. Learn what's happening not learn how to get around it (i.e. not just hack your code to the window Object):

http://jsfiddle.net/UJ85S/12/

No wrap - in <body>
Todd Motto
  • 903
  • 6
  • 10
  • I liked this answer, but I want to add some clarification, because I had to search a lot in the settings: Click the "Javascript + jQuery" dropdown and you will find the "Load type" dropdown. Then select "No wrap" :) – nyagolova Apr 24 '19 at 12:47
2

This is happening because you define myfoo inside of $(window).load(function () {...}) function (JSFIDDLE does this):

You need to declare a global function. You can do window.myfoo to declare your function instead.

window.myfoo = function (x)
{
    alert(x);
}

JSFIDDLE

But yeah, it's not a good practice to polute the global scope, that's why it's better to use $(...).on("click", function () { alert(...) }) handlers.

I discourage using on... attributes in HTML because it's also another bad practice.

Your code becomes:

function myfoo (x)
{
    alert(x);
}

var $divToAppend = $("<div id='cool_div'>")
$divToAppend.on("click", function () {
    myfoo("hello");
});

$("#some").html($divToAppend);

And here a DEMO.

Community
  • 1
  • 1
Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
  • The reason that this is required on jsfiddle is because it executes in a [closure](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures), which means that myfoo() isn't in the global scope. – jedifans Jan 18 '14 at 19:41
  • Yes pollute the global scope, great idea. This answer "works" but teaches the OP nothing about how JavaScript works. – Todd Motto Jan 18 '14 at 19:45
  • My code do not work also locally, so JSFIDDLE not the problem. But solution is nice) – Tigran Jan 18 '14 at 19:46
  • No. I code something another, got problem, build an example on jsfiddle. Same stuff - self defined function - "not defined"; – Tigran Jan 18 '14 at 19:51
  • Will go and use .click :) – Tigran Jan 18 '14 at 19:52