change
change이벤트는 요소의 변경이 끝날 때 발생한다
텍스트가 수정될 때 마다 발생하지 않고 input이나 textarea에서 포커스를 잃을 때 발생
<form>
<label> inputBox
<input type="text" name="inputBox">
</label>
</form>
<script>
const inputElem = document.forms[0].inputBox;
inputElem.addEventListener('change',(e)=>{
console.log(e.target.value);
});
</script>
위의 예제에서 inputBox에 입력 후 커서를 다른 곳에 찍어 포커스를 잃을 시에 로그가 출력된다
input
input이벤트가 오히려 change의 이름을 가지면 어땠을까 싶다
<form>
<label> inputBox
<input type="text" name="inputBox">
</label>
</form>
<script>
const inputElem = document.forms[0].inputBox;
inputElem.addEventListener('input',(e)=>{
console.log(e.target.value);
});
</script>
inputBox안의 내용이 달라질 때 마다(입력,삭제) 로그를 출력하는 예제이다
copy, paste, cut
이 3개는 동작이 동일하다
복사, 잘라내기, 붙여넣기 시에 발생하는 이벤트이다
<form>
<label> inputBox
<input type="text" name="inputBox">
</label>
</form>
<script>
const inputElem = document.forms[0].inputBox;
inputElem.addEventListener('copy',(e)=>{
alert('복사 금지입니다');
e.preventDefault();
});
</script>
inputBox안에서 복사를 시도하려고 할 때 경고문을 띄우고 preventDefault로 복사를 막는 코드
paste, cut도 동일하게 사용 가능
submit
input type="submit"이나 button태그를 눌러 폼의 submit이 이루어졌을 때 발생하는 이벤트
처음에 무식하게 submit을 버튼이 가지고 있으니까 버튼에 이벤트를 줬었다..
폼 전체가 submit하는 거니까 폼 전체에 이벤트를 건다
<form>
<label> inputBox
<input type="text" name="inputBox">
</label>
<button name="button" type="submit"> button</button>
</form>
<script>
const inputElem = document.forms[0];
inputElem.addEventListener('submit',(e)=>{
console.log('제출되었습니다');
e.preventDefault();
});
제출되면 로그가 찍히는 코드
action이 디폴트값이라 새로고침되는 것을 막기위해 preventDefalut를 줘서 새로고침을 막았다
blur, focus
blur와 focus는 완전히 반대인데
blur는 포커스를 잃을 때 발생하고 focus는 포커스를 갖고 있을 때 발생하는 이벤트이다
보통 유효성 검사 수준에서 많이 사용되는 것 같다
<form>
<label> inputBox
<input type="text" name="inputBox">
</label>
<button name="button" type="submit"> button</button>
</form>
<script>
const inputElem = document.forms[0].inputBox;
inputElem.addEventListener('focus',(e)=>{
e.target.style.border = '3px solid dodgerblue';
});
inputElem.addEventListener('blur',(e)=>{
e.target.style.border = '3px solid red';
});
</script>
위 예제는 inputBox가 포커스를 갖고 있을 때 테두리가 하늘색, 잃었을 때 빨간색을 나타내는 코드
'JavaScript' 카테고리의 다른 글
name space (0) | 2020.11.19 |
---|---|
Number() vs parseInt() (0) | 2020.11.16 |
Ajax (0) | 2020.11.08 |
form (0) | 2020.11.07 |
마우스 좌표값 (0) | 2020.10.20 |