Home > Net >  addEventListener work only on one button (multiple pages)
addEventListener work only on one button (multiple pages)

Time:11-14

I have three buttons on three pages (Signup, Login, and one button for Signout). i work with firebase. i succseed to do this but in 3 js file, i need to do this in one js file but in one file only the first button work (the first in the code). i work with js module, can I do this with onclick? someone can tell me how to do addEventlistener for more then one button in multiple pages?

i have tried if but its not work

//signup page, signup button id = signUp
signUp.addEventListener("click", (e) => {
  var fullname = document.getElementById('SignupName').value
  var email = document.getElementById('SignupEmail').value
  var password = document.getElementById('SignupPassword').value

  createUserWithEmailAndPassword(auth, email, password)
    .then((userCredential) => {
      // Signed in 
      const user = userCredential.user;

      set(ref(database, 'users/'   user.uid), {
        fullname: fullname,
        email: email
      })
      alert('successful!!!')
      // ...
    })
    .catch((error) => {
      const errorCode = error.code;
      const errorMessage = error.message;
      alert(errorMessage);
      // ..
    });
});

//login page, login button id = LogIn
LogIn.addEventListener("click", (e) => {
  var email = document.getElementById('LoginEmail').value
  var password = document.getElementById('LoginPassword').value
  signInWithEmailAndPassword(auth, email, password)
    .then((userCredential) => {
      // Signed in 
      alert("login!!!")
      const user = userCredential.user;
      window.location.href = "gamescard.html"
      // ...
    })
    .catch((error) => {
      const errorCode = error.code;
      const errorMessage = error.message;
      alert(errorMessage);
    });
});

CodePudding user response:

You have to add event listener for each button. Put a generic class on your 3 buttons, let say ".logsButton"

You select all .logsButton:

   let els_logbuts = document.querySelectorAll('.logsButton);

Now you add event listener on each:

els_logbuts.forEach((e) => e.addEventListener('click', function (e) {
    // element clicked
    let elclicked = e.target
    // ...
}));

Now you have the clicked element, take its id (elcicked.id) And call the corresponding function: login, logout...

  • Related