input의 placeholder 는 값이 입력되면 사라지는데 값이 입력 되더라도 폼 위젯의 내용이 표시되어야 할 경우가 있다. 이럴 때 placeholder를 대신해 label를 absolute로 띄워 스크립트로 입력값에 따라 조건부로 제어해주면 된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var $user_name = document.querySelectorAll('input')

function onFocus(e) {
e.target.parentElement.classList.add("on");
console.log(e.target.value);
}

function onBlur(e) {
if (e.target.value == "") {
e.target.parentElement.classList.remove("on");
}
}

for (i = 0; i < $user_name.length; i++) {
$user_name[i].addEventListener('focus', onFocus);
$user_name[i].addEventListener('blur', onBlur);
}