#is not defined at HTMLButtonElement.onclick
32 messages · Page 1 of 1 (latest)
The scope is the current context of execution in which values and expressions are "visible" or can be referenced. If a variable or expression is not in the current scope, it will not be available for use. Scopes can also be layered in a hierarchy, so that child scopes have access to parent scopes, but not vice versa.
by default, files each have their own scopes.
didnt help :/ this isnt the problem
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.
problem is that html ignores my function in test.js
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
Okay, so the issue is what I pointed out, your button function is not part of your HTML file scope.
I checked out the link but I still dont quite get what should I change :/
new to both JS and HTML
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
but it worked for a while like that 😄
then something, I dont remember what happened
Until you changed something that broke it. It could have been changing the type of your script to module since that has stricter behavior.
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.
Yes, this may have been something that affected the scoping behavior of your file. That's why I said it.
it was module even then
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.
ok ill try