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

  • 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.
主站蜘蛛池模板: 托克逊县| 砚山县| 贵州省| 霍林郭勒市| 深水埗区| 昭通市| 北宁市| 榆树市| 沙洋县| 贡嘎县| 陆河县| 揭东县| 许昌市| 铜陵市| 琼中| 德令哈市| 朝阳市| 文水县| 高雄市| 定州市| 涪陵区| 张北县| 凭祥市| 宁阳县| 广德县| 高安市| 绥中县| 拉萨市| 乐至县| 黑河市| 江源县| 云梦县| 南京市| 新民市| 高清| 永善县| 平度市| 南乐县| 五原县| 凤山市| 威信县|