Javascript

이벤트 연습 / 마우스 좌표 찍기, input + keyup 이벤트

2DC 2022. 10. 25. 18:11

이벤트에서는

각 이벤트 관련 동작들이 오브젝트로 반환이 되어, 이벤트 함수에 전달이 된다.

        요소.addEventListener('mousemove', (e) => {
            coordinate.textContent = `X: ${e.clientX}, Y: ${e.clientY}`
        })

즉, 위의 코드처럼 addEventListener에 mousemove 이벤트를 줬을 때,

  • 이벤트 핸들러(이벤트가 실행되었을 때 실행되는 함수)는
  • 이벤트 관련 동작의 오브젝트를 인수로 받을 수 있다.

 

이벤트 관련 동작의 오브젝트에는 다양한 프로퍼티가 있는데,

위 영상에서는 clientX와 clientY라는 프로퍼티를 활용해서 좌표를 표시했다.

 


이와 같이,

이벤트 타입을 알게되고,

그것이 반환한 오브젝트 내 프로퍼티들을 활용해서

JS로 적절히 조절할 수 있게 되면

웹 관련 프로그래밍을 조금 더 역동적으로 할 수 있게 될 것이다.

 

아래는 위 동영상의 전체 코드이다.

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>typewriter</title>
</head>
<body>
    <h1 class="coordinate"></h1>
    <input type="text">
    <div class="typedisplay"></div>
    <div class="display"></div>
    <script>
        const html = document.querySelector('html')
        const coordinate = document.querySelector('.coordinate')
        const input = document.querySelector('input')
        const typedisplay = document.querySelector('.typedisplay')
        const display = document.querySelector('.display')
        const typingArray = []
        html.addEventListener('mousemove', (e) => {
            coordinate.textContent = `X: ${e.clientX}, Y: ${e.clientY}`
        })

        input.addEventListener('keyup', (e) => {
            if (e.code === 'Enter') {
                typingArray.unshift(input.value)
                input.value = ''
                render()
            }
            typedisplay.innerHTML = `<p>${input.value}</p>`
        })
        
        const render = () => {
            display.innerHTML = typingArray.reduce((acc, e) => {
                acc = acc + `<h1>${e}</h1>`
                return acc
            }, '')
            
        }

    </script>
</body>
</html>

만약 독자분이 계시다면....

 

한번 쓱 읽어보시고

궁금한게 있으면 댓글로 남겨주셔요.

성심성의껏 답변드리겠습니다.