I'm trying to learn JavaScript, but the following code has been giving me a lot of trouble:
window.onload = function () {
for ( var i = 0; i < seats.length; i++) {
for ( var j = 0; j < seats.length; j++) {
document.getElementById(getSeatId(i, j)).onclick = function(evt) {
getSeatStatus(getSeatId(i, j));
};
}
}
document.getElementById("search").onclick = findSeat;
document.getElementById("male_search").onclick = findMaleSeats;
initSeats();
};
It is from an external JS file and it is the only file linked to the page. findSeat
, findMaleSeats
, getSeatId
, and initSeats
are all defined a little bit later in the file. When I double click this file, I get the following error:
Windows Script Host Error: 'window' is not defined Code: 800A1391
I already tried moving the code to other places in the file, assigning a different function (even an empty function) to window.onload
and many other things. It just seems that my computer doesn't know what window
is. And if I try to open the HTML in a browser the nothing loads (as one would expect).
Does someone know what is wrong with this?
To solve the "ReferenceError: window is not defined" error, make sure to only use the window global variable on the browser. The variable represents a window containing a DOM document and can't be used on the server side (e.g. in Node. js). If you need to define global variables in Node.
The root cause of the error Next. js is compiled/built on Node. js runtime and Node. js does not have the the window object.
To solve the "ReferenceError require is not defined" error, remove the type property if it's set to module in your package. json file and rename any files that have a . mjs extension to have a . js extension.
Trying to access an undefined variable will throw you a ReferenceError
.
A solution to this is to use typeof
:
if (typeof window === "undefined") {
console.log("Oops, `window` is not defined")
}
or a try catch:
try { window } catch (err) {
console.log("Oops, `window` is not defined")
}
While typeof window
is probably the cleanest of the two, the try catch can still be useful in some cases.
It is from an external js file and it is the only file linked to the page.
OK.
When I double click this file I get the following error
Sounds like you're double-clicking/running a .js file, which will attempt to run the script outside the browser, like a command line script. And that would explain this error:
Windows Script Host Error: 'window' is not defined Code: 800A1391
... not an error you'll see in a browser. And of course, the browser is what supplies the window
object.
ADDENDUM: As a course of action, I'd suggest opening the relevant HTML file and taking a peek at the console. If you don't see anything there, it's likely your window.onload
definition is simply being hit after the browser fires the window.onload
event.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With