Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't my JavaScript working in JSFiddle?

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).

like image 440
Larry Cinnabar Avatar asked Mar 25 '11 10:03

Larry Cinnabar


People also ask

What is better than JSFiddle?

CodePen, jQuery, CodeSandbox, StackBlitz, and Visual Studio Code are the most popular alternatives and competitors to JSFiddle.

How do I run a function in JSFiddle?

With JSFiddle, you can write code in the JavaScript box and then execute it by clicking the Run button on the menu bar at the top of the JSFiddle page.


1 Answers

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.

like image 190
zalun Avatar answered Oct 10 '22 11:10

zalun