로그인 버튼 활성화 시, 삼항 연산자로 구현!
const thisIsButton = document.getElementsByClassName('button')[0];
const thisIsId = document.getElementById('id');
const thisIsPw = document.getElementById('pw');
// document 객체에 접근하여 원하는 값을 가진 요소를 변수에 할당
function activeButton() {
const inputId = thisIsId.value.length;
const inputPw = thisIsPw.value.length;
// 각 아이디, 비밀번호 input창의 값을 변수에 할당.
return inputId > 0 && inputPw > 0 ? (
// input 창에 입력되는 값들이 각각 1개 이상인 경우 라는 조건.
// 즉, 백스페이스를 눌러서 값이 0이 되는 경우에는 false가 되는 것이다.
thisIsButton.disabled = true,
thisIsButton.style.backgroundColor = "#0000ff") : (
// 참인 경우, 버튼 활성화 & 배경색 변경
thisIsButton.disabled = false,
thisIsButton.style.backgroundColor = "#c4e1fb"
)
// 거짓인 경우, 버튼 비활성화 & 기존 배경색 유지
}
thisIsId.addEventListener('keyup', activeButton)
thisIsPw.addEventListener('keyup', activeButton)
// 비밀번호 먼저 입력하는 경우도 있기에 각 input창에 똑같이 적용.
삼항연산자로 구현한 것을 거의 포기했었다.
그런데 자꾸 신경쓰여서 결국 자리를 잡고, 구현하려고 자리를 잡았다.
삼항연산자로 구현하는게 익숙치 않아서 어려웠다.
true
인 경우, 2개의 결과값(버튼 활성화, 배경색 변경)을 가져와야 하는데 이 부분이 도통 구현이 안됐었다.
변수에 함수 할당해서 표현을 해야할지 고민이 많았다.
함수로 할당한다면 true
, false
2개를 만들어야 하는 거 같은데 그러면 기존 코드보다 더 길어지기에 이 코드는 아닌 것 같았다.
인터넷에 삼항연산자를 엄청 찾아보았다.
true
로 표현해야 코드가 많은 경우,
소괄호( )
를 이용하여, 실행코드를 묶으면 됐었다.
간단했지만 삼항연산자를 어떻게 사용할 지 몰랐던 나에게는 유레카였다.
앞으로 삼항연산자 쓸 때, 이 부분에 대해서는 막힘 없이 잘 할 수 있을 거 같다.
그런데 기존 내 if문과 비교해도면 딱히 크게 많이 코드가 간결해 지지 않았다.
아무래도 아직도 내 코드가 수정할 부분이 많다는 뜻이겠지..
그래도 삼항연산자로 구현을 해냈다는 것에 정말 만족만족 대만족이다..👍🏻
activeButton = () => {
const thisIsButton = document.querySelector('.button');
const thisIsId = document.querySelector('#id');
const thisIsPw = document.querySelector('#pw');
// 'querySelector'로 값을 가져옴.
const inputId = thisIsId.value.includes('@') && thisIsId.value.length > 1;
const inputPw = thisIsPw.value.length >= 5;
const conditions = inputId && inputPw;
// 조건을 각 변수에 할당
const activeBtn = () => {
thisIsButton.disabled = false;
thisIsButton.style.backgroundColor = '#0000ff';
};
// 'true' 인 경우
const inActiveBtn = () => {
thisIsButton.disabled = true;
thisIsButton.style.backgroundColor = '#c4e1fb';
};
// 'false'인 경우
return conditions ? activeBtn() : inActiveBtn();
};
// 간결해진 삼항연산자!