0

I have a simple javascript onclick function call that isn't working, and I just keep staring and I cant see anything wrong, I feel like I must be overlooking something super simple but I just cant see what!

https://jsfiddle.net/sanfly/tob4dugj/

HTML:

<p id="demo"></p>
<button onclick="myFunction()">Click me</button>

JS:

function myFunction() {
  document.getElementById("demo").innerHTML = "Hello World";
}

Error:

Uncaught ReferenceError: myFunction is not defined at HTMLButtonElement.onclick
31piy
  • 23,323
  • 6
  • 47
  • 67
Sanfly
  • 1,021
  • 1
  • 11
  • 19

1 Answers1

1

This is because JSFiddle is putting the JavaScript in an implicit closure that you can't see. Ergo, your function is defined locally in that scope, and the button can't access it.

Making it global (while a terrible idea for other reasons), solves this:

myFunction = function() { //make it global
  document.getElementById("demo").innerHTML = "Hello World";
}

Updated Fiddle

This would also be a good time to move away from inline (i.e. in-HTML) event handling and instead move towards centralised addEventListener().

Mitya
  • 33,629
  • 9
  • 60
  • 107