Pascal
Pascal

Reputation: 95

Inline JS onclick Function Call Error

I want to make each button call a function called sDM() and input a different code but whenever I do this, I get:

ReferenceError: sDM is not defined at HTMLButtonElement.onclick

<button onclick="sDM(38)" style="width: 100%">&#8593;</button>
<br>
<button onclick="sDM(37)"  style="width: 47%">&#8592;</button>&nbsp;
<button onclick="sDM(39)" style="width: 47%">&#8594;</button>
<br>
<button onclick="sDM(40)" style="width: 100%">&#8595;</button>

My function:

  function sDM (dN) {
           snake.setDirection(directions[dN])
         }

Upvotes: 0

Views: 106

Answers (1)

Fabien Greard
Fabien Greard

Reputation: 1894

(could be)Looks like that your javascript is loaded before your html. Please insert your javascript inside one of those listeners

document.addEventListener( 'DOMContentLoaded', function( event ) {
    // Do something
});

or

window.addEventListener( 'load', function( event ) {
    // Do something
});

Here's the explanation.

Upvotes: 1

Related Questions