- 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.
- Computer Vision for the Web
- YARN Essentials
- Building a Quadcopter with Arduino
- Linux命令行與shell腳本編程大全(第4版)
- Android系統(tǒng)級(jí)深入開(kāi)發(fā)
- Android編程權(quán)威指南(第4版)
- Spring Boot從入門(mén)到實(shí)戰(zhàn)
- C#程序開(kāi)發(fā)參考手冊(cè)
- Python程序設(shè)計(jì)現(xiàn)代方法
- Storm Real-Time Processing Cookbook
- Visual FoxPro程序設(shè)計(jì)
- Go Programming Cookbook(Second Edition)
- Java面向?qū)ο蟪绦蛟O(shè)計(jì)(第3版)
- Mastering Rust
- 跟著迪哥學(xué)Python數(shù)據(jù)分析與機(jī)器學(xué)習(xí)實(shí)戰(zhàn)