Languages/JS

[인터랙티브 Javascript] 04. 다양한 이벤트 알아보기

Dev다D 2021. 3. 1. 22:10
반응형

똑Talk한 Enter키!

 

HTML/CSS, 그리고 자바스크립트를 활용해서 웹으로 간단한 채팅 앱을 만들었습니다. textarea 태그에 메시지를 입력하고 오른편에 있는 send 버튼을 클릭하면 화면에 내가 입력한 메시지가 나는데요.

text 타입의 input 태그나 textarea 태그를 자바스크립트로 선택한 다음에 해당 요소 노드의 value 프로퍼티를 활용하면 해당 태그에 입력된 값을 다룰 수 있습니다.

그런데 한 가지 아쉬운 점은 키보드로 메시지를 입력하고 나면, 마우스를 움직여서 send 버튼을 눌러야 한다는 겁니다.

아쉬운 규리를 위해서 textarea 태그에서 enter 키를 누르면 sendMyText 함수가 호출되는 코드를 추가해 주세요.

코드를 완성했을 때 아래 조건들이 지켜져야 합니다.

  • enter 키로 메시지를 전송하고 나면 textarea 태그는 초기화가 제대로 되어야 합니다.
  • shift + enter 일때는 줄바꿈이 일어나야 합니다.
  • keypress 타입으로 이벤트 핸들러가 등록되어야 합니다.

 


const chatBox = document.querySelector('#chat-box');
const input = document.querySelector('#input');
const send = document.querySelector('#send');

function sendMyText() {
    const newMessage = input.value;
    if (newMessage) {
        const div = document.createElement('div');
        div.classList.add('bubble', 'my-bubble');
        div.innerText = newMessage;
        chatBox.append(div);
    } else {
        alert('메시지를 입력하세요...');
    }

    input.value = '';
}

send.addEventListener('click', sendMyText);

function sendMyTextByEnter (e) {
    if (e.key === 'Enter' && !e.shiftKey) {
        sendMyText();
        e.preventDefault();
    }
}

input.addEventListener('keypress', sendMyTextByEnter);

본 내용은 Codeit의  'Javascript 중급' 강의를
참고하여 작성한 내용입니다.

 

반응형