官术网_书友最值得收藏!

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.
主站蜘蛛池模板: 宜黄县| 兰坪| 娱乐| 富源县| 林甸县| 永顺县| 蕉岭县| 新乡县| 凤冈县| 岑巩县| 监利县| 安泽县| 甘孜| 南丹县| 洮南市| 鄯善县| 郑州市| 马公市| 犍为县| 锡林郭勒盟| 石柱| 镇江市| 达拉特旗| 龙江县| 团风县| 黄平县| 大宁县| 吕梁市| 哈巴河县| 合水县| 新丰县| 西平县| 白山市| 库尔勒市| 绵竹市| 越西县| 铜川市| 建瓯市| 陇南市| 九龙县| 伊金霍洛旗|