Events are an important part of interacting with users and handling actions. JavaScript provides a convenient way to attach event handler functions to components on a web page.
To use an event in JavaScript, we need to attach an event handler function to a component on the web page. There are many different types of events, such as click, mouseover, keydown, and many more.
Here is a simple example of using an event:
//Giả xử ở HTML có button với id là myButton
let button = document.getElementById('myButton');
function handleClick() {
console.log('Button đã được nhấn!');
}
button.addEventListener('click', handleClick);
In the example above, we attached the handleClick function to the click event of a button. When the user clicks on that button, the handleClick function will be called and print a message on the console.
When handling an event, we can access information about the event and the root component that the event occurred on. This allows us to interact with data and change the properties of the component.
function handleClick(event) {
console.log('Button đã được nhấn!');
console.log('Thông tin về sự kiện:', event);
console.log('Thành phần gốc:', event.target);
}
button.addEventListener('click', handleClick);
In the example above, we added the event parameter to the handleClick function. Through this parameter, we can access information about the event, such as event.target to get the root component of the event.
Here are some examples of using and handling events in JavaScript:
let button = document.getElementById('myButton');
function handleClick() {
console.log('Button đã được nhấn!');
}
button.addEventListener('click', handleClick);
function handleMouseOver(event) {
console.log('Con trỏ chuột đã đi qua nút!');
console.log('Thông tin về sự kiện:', event);
}
button.addEventListener('mouseover', handleMouseOver);
function handleKeyPress(event) {
console.log('Bạn đã nhấn phím:', event.key);
}
document.addEventListener('keydown', handleKeyPress);
In the example above, we used events like click, mouseover, and keydown. Each event is attached to a corresponding event handler function. When the events occur, the event handler functions are called and print the corresponding information on the console.