0

I am unable to call a function from HTML file. This seems simple and my code matches what I've seen in similar SO answers, but I am missing something still. I know the JS is loading/running because the game in the canvas is working. Edit: Chrome console returns "testFunction is not defined" meaning the JS is NOT loaded. Why?

This is a test in the JS file:

function testFunction(){
    alert("It works!");
}

and it's called from the HTML like so:

<button type="button" onclick="testFunction()" id="testButton">Test</button>

Here's the JSFiddle http://jsfiddle.net/goldrunt/SeAGU/

10
  • 1
    The fiddle doesn't match your code
    – Serge K.
    Commented Feb 22, 2014 at 17:53
  • Oops you're right just updated.
    – MattO
    Commented Feb 22, 2014 at 17:55
  • 1
    Consider keeping your Javascript and HTML separate. Unobtrusive JavaScript and EventTarget.addEventListener should help.
    – Xotic750
    Commented Feb 22, 2014 at 17:57
  • They are separate. The script is called externally.
    – MattO
    Commented Feb 22, 2014 at 17:58
  • 1
    Sorry I can't see your update on the fiddle
    – Serge K.
    Commented Feb 22, 2014 at 18:01

2 Answers 2

3

When using JSFiddle, your code is wrapped in an "onLoad" function (unless you specifically tell it otherwise).

Functions defined inside functions exist only in that function, so your testFunction, for example, is only accessible in the onLoad function that is your JS block of code. HTML from the outside can't access it.

Try changing "onLoad" to "no wrap - body" in the relevant option on JSFiddle.

3

Unobtrusive JavaScript examples.

Javascript events

Like this using on + handler, is one way and most compatible.

HTML

<button type="button" id="testButton">Test</button>

Javascript

function testFunction() {
    alert("It works!");
}

window.onload = function () {
    document.getElementById('testButton').onclick = testFunction;
};

On jsFiddle

Or using the modern method EventTarget.addEventListener

Javascript

function testFunction() {
    alert("It works!");
}

window.addEventListener('load', function () {
    document.getElementById('testButton').addEventListener('click', testFunction, false);
}, false);

On jsFiddle

GlobalEventHandlers.onload

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.