Why isn't my JavaScript working in JSFiddle?

Larry Cinnabar picture Larry Cinnabar · Mar 25, 2011 · Viewed 51.8k times · Source

I can't find out what is the problem with this JSFiddle.

HTML:

<input type="button" value="test" onclick="test()">

JavaScript:

function test(){alert("test");}

And when I click on button - nothing happened. The console says "test not defined"

I've read the JSFiddle documentation - there it says that JS code is added to <head> and HTML code is added to <body> (so this JS code is earlier than html and should work).

Answer

zalun picture zalun · Apr 29, 2011

If you do not specify the wrap setting it defaults to "onLoad". This results with all JavaScript being wrapped in a function run after result has been loaded. All variables are local to this function thus unavailable in the global scope.

Change the wrapping setting to "no wrap" and it'll work:

http://jsfiddle.net/zalun/Yazpj/1/

I switched the framework to "No Library" as you don't use any.