Reputation: 729
There are two <input type="text">
form elements and a button
than I'm attempting to attach event handlers to via .forEach()
. Upon trying to access each element the following error is being raised:
Uncaught TypeError: Cannot read property '#<HTMLInputElement>' of undefined
However, if I hard code the event handlers individually to each one of those elements the subject error is not raised. What is going on for this to occur?
JS
Fails
const login_container = document.querySelector(".login_form_container");
const username_field = document.getElementById("id_login_username");
const password_field = document.getElementById("id_login_password");
const post_login = document.getElementById("post_login");
login_container.addEventListener("mouseout", function(event) {
this.classList.add("shift");
})
[post_login, username_field, password_field].forEach((widget) => {
widget.addEventListener("mouseover", function(event) {
login_container.classList.remove("shift");
})
})
Passes
post_login.addEventListener("mouseover", function(event) {
login_container.classList.remove("shift");
})
username_field.addEventListener("mouseover", function(event) {
login_container.classList.remove("shift");
})
password_field.addEventListener("mouseover", function(event) {
login_container.classList.remove("shift");
})
HTML
<div class="login_form_container shift slide">
<form class="login_form">
{% for field in login_form %}
{{ field }}
{% endfor %}
<button id="post_login" class="login_button" type="button">Access</button>
</form>
</div>
Upvotes: 1
Views: 594
Reputation: 618
JSFiddle shows a warning explaining what's happening.
You don't have any semicolons after your .addEventListener
calls, which means the JavaScript parser interprets the array literal as an indexing operator on the result of addEventListener
.
And since post_login
is not a valid index into undefined
(the return value), it throws a TypeError
.
login_container.addEventListener(...)[post_login, ...].forEach(...)
You can fix it by simply adding semicolons after each call.
Upvotes: 2