0

I have this simple code which has nothing wrong with it and it runs here but not on JSFiddle. On inspecting the console I find the following error

Uncaught ReferenceError: fn is not defined

LINK TO FIDDLE

var fn = {
  one: function() {
    alert('1')
  },
  two: function() {
    alert('2')
  },
  three: function() {
    alert('3')
  }
};
<button onclick='fn.one()'>1</button>
<button onclick='fn.two()'>2</button>
<button onclick='fn.three()'>3</button>
Anubhav
  • 7,138
  • 5
  • 21
  • 33

5 Answers5

1

This is just a JSFiddle feature. JSFiddle, by default, wraps all your code in a $(document).ready() handler. To get your JS out of the wrapper and back into the flow of the normal DOM, just select the JSFiddle option under 'Frameworks & Extensions' and change it from 'onLoad' to 'No wrap - in head' or 'No wrap - in body'

bowheart
  • 4,616
  • 2
  • 27
  • 27
1

Change the drop down in jsfiddle from onLoad to No wrap - in head OR No wrap - in body.

Woodchipper
  • 530
  • 6
  • 12
1

Change the option on the left from onLoad to one of the no wrap (i.e. no wrap - in <head> or no wrap - in <body> options and it runs with no problems.

Chris Franklin
  • 3,864
  • 2
  • 16
  • 19
1

It's because jsfiddle sandboxes your code in a closure.

You can see that you wrote var fn (which makes a local var), just remove the var statement to make it global and you will be able to call it the way you are now.

Though, I'd advise you to use addEventListener().

topheman
  • 7,422
  • 4
  • 24
  • 33
1

This code on jsfiddle doesnt work because this is how scope of variables works in JavaScript.

You can see that if I change only a few characters from

var fn = // the rest of code ...

to

window.fn = // the rest of code ...

Your example works "correctly" - http://jsfiddle.net/v3gsmnvq/7/

Read about scopes even here on SO: What is the scope of variables in JavaScript?

Community
  • 1
  • 1
Dawid Karabin
  • 5,113
  • 1
  • 23
  • 31