- JavaScript by Example
- Dani Akash S
- 276字
- 2021-07-02 18:39:08
Adding tasks by hitting Enter button
Well, this is one way of adding tasks, but some users prefer adding tasks directly by hitting the Enter button. For that, let's use event listeners to detect the Enter key press in the <input> element. We can also use the onchange attribute of our <input> element, but let's give event listeners a try. The best way to add event listeners to a class is to call them in the constructor so that the event listeners are set up when the class is initialized.
So, in our class, create a new function addEventListeners() and call it in our constructor. We are going to add event listeners inside this function:
constructor() {
...
this.addEventListeners();
}
addEventListeners() {
document.getElementById('addTask').addEventListener('keypress', event => {
if(event.keyCode === 13) {
this.addTask(event.target.value);
event.target.value = '';
}
});
}
And that's it! Reload Chrome, type in the text, and hit Enter. This should add tasks to our list just like how the add button works. Let's go through our new event listener:
- For every keypress happening in the <input> element with the ID addTask, we run the callback function with the event object as the parameter.
- This event object contains the keycode of the key that was pressed. For the Enter key, the keycode is 13. If the key code is equal to 13, we simply call the this.addTask() function with the task's text event.target.value as its parameter.
- Now, the addTask() function handles adding the task to the list. We can simply reset <input> back to an empty string. This is a great advantage of organizing every operation into functions. We can simply reuse the functions wherever they're needed.
- 案例式C語言程序設(shè)計
- Web Application Development with R Using Shiny(Second Edition)
- Apache Spark Graph Processing
- R語言數(shù)據(jù)可視化實(shí)戰(zhàn)
- Windows Phone 7.5:Building Location-aware Applications
- 愛上micro:bit
- JavaScript腳本特效編程給力起飛
- 大學(xué)計算機(jī)基礎(chǔ)
- PHP與MySQL權(quán)威指南
- 奔跑吧 Linux內(nèi)核
- jQuery從入門到精通(微課精編版)
- 算法超簡單:趣味游戲帶你輕松入門與實(shí)踐
- 算法精解:C語言描述
- Ubuntu Server Cookbook
- 可視化H5頁面設(shè)計與制作:Mugeda標(biāo)準(zhǔn)教程