Home > database >  Getting multiple elements from the dom
Getting multiple elements from the dom

Time:11-26

I have an authentication page, to navigate between the forms I use javascript. My code is this:

const btnSignIn = document.querySelector('.form-controls__label-signin');
const btnSignUp = document.querySelector('.form-controls__label-signup');
const btnForgot = document.querySelector('.signin-form .forgot-link');
const btnForgotBack = document.querySelector('.forgot-form .forgot-back');
const titleLogin = document.querySelector('.header-auth__login');
const formLogin = document.querySelector('.signin-form');
const formControls = document.querySelector('.form-controls');

btnSignUp.addEventListener('click', function(){
  titleLogin.style.marginLeft = '-33.33%';
  formLogin.style.marginLeft = '-33.33%';
})

btnForgot.addEventListener('click', function(){
  titleLogin.style.marginLeft = '-66.66%';
  formLogin.style.marginLeft = '-66.66%';
  formControls.style.display = 'none';
})

btnForgotBack.addEventListener('click', function(){
  formLogin.style.marginLeft = '0%';
  titleLogin.style.marginLeft = '0%';
  formControls.style.display = 'flex';
})

btnSignIn.addEventListener('click', function(){
  formLogin.style.marginLeft = '0%';
  titleLogin.style.marginLeft = '0%';
})

How to make the code cleaner? Can someone help me?

CodePudding user response:

I found a solution that made the code cleaner:

let elements = {};

const allClass = ['jsHeaderLogin', 'jsLabelSignin', 'jsLabelSignup', 
  'jsFormControls', 'jsSigninForm', 'jsForgotLink', 'jsForgotBack'];

allClass.forEach(item => elements = {
  ...elements,
  [item]: document.querySelector(`.${item}`)
});

const { jsHeaderLogin, jsLabelSignin, jsLabelSignup, jsFormControls, 
  jsSigninForm, jsForgotLink, jsForgotBack } = elements;

jsLabelSignup.addEventListener('click', function(){
  jsHeaderLogin.style.marginLeft = '-33.33%';
  jsSigninForm.style.marginLeft = '-33.33%';
})

jsForgotLink.addEventListener('click', function(){
  jsHeaderLogin.style.marginLeft = '-66.66%';
  jsSigninForm.style.marginLeft = '-66.66%';
  jsFormControls.style.display = 'none';
})

jsForgotBack.addEventListener('click', function(){
  jsHeaderLogin.style.marginLeft = '0%';
  jsSigninForm.style.marginLeft = '0%';
  jsFormControls.style.display = 'flex';
})

jsLabelSignin.addEventListener('click', function(){
  jsHeaderLogin.style.marginLeft = '0%';
  jsSigninForm.style.marginLeft = '0%';
})

I had to include a class for JavaScript, to facilitate code maintenance.

  • Related