#is not defined at HTMLButtonElement.onclick

32 messages · Page 1 of 1 (latest)

merry jasper
#

hey there! created a button in html to trigger my model switching function. It worked for a while then something happened and it keeps returning this error

sullen dragon
#

by default, files each have their own scopes.

merry jasper
#

didnt help :/ this isnt the problem

sullen dragon
#

It's the problem, not the solution.

#

Your Root HTML file has a different scope than the JavaScript file.

#

Although they do share the same global scope, but naming a function like you did doesn't pass it through the global scope, not that that's necessarily the best way to do things though.

#

Huh, actually, now that I think about it, you never actually said what the problem was.

merry jasper
#

problem is that html ignores my function in test.js

sullen dragon
#

Why don't you screenshot the error that your console is showing you?

#

Because ignoring is not normally a keyword that JavaScript consoles indicate on their own

merry jasper
#

not sure if it is readable

sullen dragon
#

Okay, so the issue is what I pointed out, your button function is not part of your HTML file scope.

merry jasper
#

I checked out the link but I still dont quite get what should I change :/

#

new to both JS and HTML

sullen dragon
#

One way to do it is to give your button an ID, and then use document.getElementById() to find your button from inside of your JavaScript file, and attach the click listener there.

#

The JavaScript files can access the document functions since they are part of the global scope, but your button function isn't part of the global scope and can't find the function in your JavaScript file

#

I would suggest doing that instead of using the onclick property on your button

merry jasper
#

but it worked for a while like that 😄

#

then something, I dont remember what happened

sullen dragon
merry jasper
#

oh my script is a module

sullen dragon
#

The script may have also been embedded in the page instead of linked from it, or maybe your script was loaded in before the button.

sullen dragon
merry jasper
#

it was module even then

sullen dragon
#

Depending on how the on click property creates itself, it may have been the order of your HTML elements. It's possible that property on your button was creating its own scope in which the script was not defined yet, in other words, maybe your JavaScript file was included above the button and you moved it below.

#

There are a lot of possibilities, however, using JavaScript to attach the event listener instead of a property is what most people do these days since it's easier to keep track of.

merry jasper
#

ok ill try