28일 10월 2019
이 글은 다음 언어로만 작성되어 있습니다. English, 日本語, Русский, Türkçe, 简体中文. 한국어 번역에 참여해주세요.

Events: change, input, cut, copy, paste

Let’s cover various events that accompany data updates.

Event: change

The change event triggers when the element has finished changing.

For text inputs that means that the event occurs when it loses focus.

For instance, while we are typing in the text field below – there’s no event. But when we move the focus somewhere else, for instance, click on a button – there will be a change event:

<input type="text" onchange="alert(this.value)">
<input type="button" value="Button">

For other elements: select, input type=checkbox/radio it triggers right after the selection changes:

<select onchange="alert(this.value)">
  <option value="">Select something</option>
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
  <option value="3">Option 3</option>
</select>

Event: input

The input event triggers every time after a value is modified by the user.

Unlike keyboard events, it triggers on any value change, even those that does not involve keyboard actions: pasting with a mouse or using speech recognition to dictate the text.

For instance:

<input type="text" id="input"> oninput: <span id="result"></span>
<script>
  input.oninput = function() {
    result.innerHTML = input.value;
  };
</script>

If we want to handle every modification of an <input> then this event is the best choice.

On the other hand, input event doesn’t trigger on keyboard input and other actions that do not involve value change, e.g. pressing arrow keys while in the input.

Can’t prevent anything in oninput

The input event occurs after the value is modified.

So we can’t use event.preventDefault() there – it’s just too late, there would be no effect.

Events: cut, copy, paste

These events occur on cutting/copying/pasting a value.

They belong to ClipboardEvent class and provide access to the data that is copied/pasted.

We also can use event.preventDefault() to abort the action, then nothing gets copied/pasted.

For instance, the code below prevents all such events and shows what we are trying to cut/copy/paste:

<input type="text" id="input">
<script>
  input.oncut = input.oncopy = input.onpaste = function(event) {
    alert(event.type + ' - ' + event.clipboardData.getData('text/plain'));
    return false;
  };
</script>

Please note, that it’s possible to copy/paste not just text, but everything. For instance, we can copy a file in the OS file manager, and paste it.

There’s a list of methods in the specification that can work with different data types including files, read/write to the clipboard.

But please note that clipboard is a “global” OS-level thing. Most browsers allow read/write access to the clipboard only in the scope of certain user actions for the safety, e.g. in onclick event handlers.

Also it’s forbidden to generate “custom” clipboard events with dispatchEvent in all browsers except Firefox.

Summary

Data change events:

Event Description Specials
change A value was changed. For text inputs triggers on focus loss.
input For text inputs on every change. Triggers immediately unlike change.
cut/copy/paste Cut/copy/paste actions. The action can be prevented. The event.clipboardData property gives read/write access to the clipboard.

과제

중요도: 5

예금 잔고와 이자율을 입력하면 주어진 기간 후에 잔고가 어떻게 될지 알려주는 인터페이스를 만들어보세요.

데모는 다음과 같습니다.

입력값이 변경되면 출력값도 즉시 변경되어야 합니다.

공식은 아래와 같습니다.

// initial: 계산 전의 잔고
// interest: 이자율. 0.05는 연 5%의 이자율을 의미합니다.
// years: 예금 유치 기간으로, 연 단위
let result = Math.round(initial * (1 + interest * years));

샌드박스를 열어 정답을 작성해보세요.

튜토리얼 지도

댓글

댓글을 달기 전에 마우스를 올렸을 때 나타나는 글을 먼저 읽어주세요.
  • 추가 코멘트, 질문 및 답변을 자유롭게 남겨주세요. 개선해야 할 것이 있다면 댓글 대신 이슈를 만들어주세요.
  • 잘 이해되지 않는 부분은 구체적으로 언급해주세요.
  • 댓글에 한 줄짜리 코드를 삽입하고 싶다면 <code> 태그를, 여러 줄로 구성된 코드를 삽입하고 싶다면 <pre> 태그를 이용하세요. 10줄 이상의 코드는 plnkr, JSBin, codepen 등의 샌드박스를 사용하세요.