I have an event listener listening to the submission of form which will be sent to firebase auth. A few hours ago, it was working fine. But suddenly, it just stopped. No error nothing. No event listeners were working. I restarted vs code and my computer. Where event listeners were defined -
import { smoothScroll } from './animations.js';
import { signup, logout } from './auth.js';
smoothScroll();
// Elements
const signupForm = document.querySelector('#signup-form');
const logoutBtn = document.querySelector('#logout-btn');
console.log(signupForm);
signupForm.addEventListener('submit', signup);
logoutBtn.addEventListener('click', logout);
Actual functions -
export function signup(e) {
e.preventDefault();
console.log('Sugb');
// User info
const email = signupForm['email'].value;
const password = signupForm['password'].value;
// Sign up
auth
.createUserWithEmailAndPassword(email, password)
.then((cred) => {
document.querySelector('.alert').classList.add('alert--show');
document.querySelector('.alert').textContent = 'User signed up';
loginState = true;
signupForm.reset();
})
.catch((error) => {
document
.querySelector('.alert')
.classList.remove('alert-success')
.add('alert-danger')
.add('alert--show');
document.querySelector('.alert').textContent = error.message;
});
}
export function logout(e) {
console.log('Logout');
alert('Logout');
}
Through a bit of debugging I found out that my functions were not getting called. This is the github repo https://github.com/akashshyamdev/doubt1 in case you need more info. Thanks in advance.
Since the signup form is present, when you add the event listener, but the event callback function is not called, I assume you changed the form after the event listener addition.
For this you must delegate the event to an element that is always there, typically the document
. As the MDN doc says about the submit_event that it bubbles up, we can do this
Instead of signupForm.addEventListener('submit', signup);
do this
document.addEventListener('submit', function(e) {
if (e.target.closest('#signup-form')) {
return signup(e);
}
return false;
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.