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).
The function is being defined inside a load handler and thus is in a different scope. As @ellisbben notes in the comments, you can fix this by explicitly defining it on the
window
object. Better, yet, change it to apply the handler to the object unobtrusively: http://jsfiddle.net/pUeue/Note applying the handler this way, instead of inline, keeps your HTML clean. I'm using jQuery, but you could do it with or without a framework or using a different framework, if you like.
Change wrap setting in the Frameworks & Extensions panel, to "No wrap-in
<body>
"There is another way, declare your function into a variable like this :
jsFiddle
Details
EDIT (based on the comments of @nnnnnn)
@nnnnnn :
When you define a function like this :
The function is defined locally, but when you define your function without
var
:test
is defined on thewindow
object which is at the top level scope.Like @zalun say :
But if you use this syntax :
You have an access to the function
test
because it's defined globallyReferences :
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.
There is no problem with your code.Just choose the extension onLoad() from right side.