Dropdown-SelectBox를 움직이게 만들던 중에 문제가 발생했다.
이 순서대로 동작해야 하는데 언어 클릭 시, blur 이벤트가 먼저 발생해버리는 것이다.
click 이벤트 코드를 먼저 작성하고 blur 이벤트 코드를 나중에 작성해 봤지만 역시 소용없었다🥲
selectBtn.addEventListener('click', () => {
selectBtn.classList.toggle('on');
});
listBtn.forEach(item => {
item.addEventListener('click', (e) => {
const btnName = e.currentTarget.textContent;
selectBtn.textContent = btnName;
});
});
selectBtn.addEventListener('blur', () => {
selectBtn.classList.remove('on');
});
구글링을 통해 알게 된 사실!
mouse를 눌렀다가 떼는 순간 mouseup과 동시에 click이 발생한다. mouse를 누른다고 바로 click이 아니었던 것이다. 그러니까 계속 누르고만 있으면 click 이벤트는 발생하지 않는다고 볼 수 있다.
즉, mousedown
→ blur
→ mouseup
→ click
순서로 이벤트가 발생한다.
click 이벤트보다 blur 이벤트가 먼저 발생하기 때문에 이런 문제가 생겼던 것.
blur 전에 일어나는 이벤트는 mousedown 이벤트다!
click
→ mousedown
으로 바꿔주면 해결!
// 버튼 토글
selectBtn.addEventListener('mousedown', () => {
selectBtn.classList.toggle('on');
});
// 버튼 블러
selectBtn.addEventListener('blur', () => {
selectBtn.classList.remove('on');
});
// 선택한 언어 버튼에 반영
listBtn.forEach(item => {
item.addEventListener('mousedown', (e) => {
const btnName = e.currentTarget.textContent;
selectBtn.textContent = btnName;
});
});