0

I want to run a function inside an object by onclick, but it doesn't work. Here is the code:

JSCode:

var jn = {
  alertText: function(){
    alert(arguments[0]);
  } 
};

HTML:

<a href="#" onclick="jn.alertText('hi')">[ClickHere]</a>

JSFiddle: http://jsfiddle.net/dotku/Nqh4S/2/

tymeJV
  • 103,943
  • 14
  • 161
  • 157
Weijing Jay Lin
  • 2,991
  • 6
  • 33
  • 53
  • 1
    That's not valid JSON, but it is perfectly valid JavaScript: [**demo**](http://jsfiddle.net/8LsCq/) – p.s.w.g Mar 13 '14 at 15:50
  • Works like a charm here: http://jsfiddle.net/4Dff8/ – tymeJV Mar 13 '14 at 15:51
  • 1
    OK but tell him that it works because JSFiddle isn't wrapping the JS in a "load" function, and so your methods are in the `window`. – Ian Clark Mar 13 '14 at 15:52
  • possible duplicate of [Onclick event not firing on jsfiddle.net](http://stackoverflow.com/questions/9114747/onclick-event-not-firing-on-jsfiddle-net) – p.s.w.g Mar 13 '14 at 15:52

1 Answers1

1

Take out the var statement and it will work. The var statement scopes it to that particular script file or tag, not the window object. DOM event handlers need to be scoped to something that's attached to the window object at some point.

Mike Thomsen
  • 36,828
  • 10
  • 60
  • 83