How do I fix an onclick that isn't working when I import a JavaScript function into my HTML file

Viewed 38

Edit: I forgot to mention that I am doing it on pythonanywhere, and check for errors on the console of the inspect tool

I have a button formatted like the one below, but when ever I try and click it, it says that the function is undefined; even though I have it imported correctly.

The button is formatted like this:

<button type="button" id="ManualGain" class="buttons" onclick="IncreaseBal()">Press me for money</button>

The import is formatted like this:

<script type="text/html" src="GameCode.js"></script>

And here is the IncreaseBal function in GameCode.js:

function IncreaseBal() {
   GameVars.balance += 10
   document.getElementById("Balance").innerText = "Balance: " + GameVars.balance
}

The GameVar function is pretty much formatted as:

var GameVars = {
   balance = 0,
   ...
}

However, I haven't been able to get it to work.

1 Answers
<script type="text/html" src="GameCode.js"></script>

You are using the type attribute to tell the browser to expect an HTML document when it requests the URL in the src attribute. HTML documents are not JavaScript programs. Since the browser doesn't know what to do with a <script> written in HTML, it doesn't do anything with it.

Omit the type attribute for regular JavaScript programs.

You can say type="text/javascript" but this only introduces the possibility of making an error.

You should use type="module" if your script is loading a JavaScript module (which doesn't appear to be the case here).


If you had used this validator it would have spotted the error for you:

Error: A script element with a src attribute must not have a type attribute whose value is anything other than the empty string, a JavaScript MIME type, or module.


Since the script isn't loading at present, it won't be triggering an error on your developer tools console yet but:

var GameVars = {
   balance = 0,

Object literal syntax uses name: value not name = value.


Aside

function IncreaseBal() {
var GameVars = {

Note that idiomatic JavaScript reserves variable names starting with capital letters for classes and constructor functions (i.e. things designed to be used with the new keyword). You shouldn't use that naming convention for regular functions and objects.


Aside

Intrinsic event attributes come with a host of issues, including some very unexpected scoping rules. Best practise is to avoid them in favour of binding event listeners using JavaScript.

Related