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/

4
  • 1
    That's not valid JSON, but it is perfectly valid JavaScript: demo Commented Mar 13, 2014 at 15:50
  • Works like a charm here: jsfiddle.net/4Dff8 Commented Mar 13, 2014 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. Commented Mar 13, 2014 at 15:52
  • possible duplicate of Onclick event not firing on jsfiddle.net Commented Mar 13, 2014 at 15:52

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.