Manipulação de Eventos
GlobalEventHandlers
Hierarchy
Registering on-event handlers
HTML attribute named on(eventtype):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<h1>Lorem ipsum</h1>
<button onclick="window.print()">Print</button>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<h1>Lorem ipsum</h1>
<button onclick="window.print()">Print</button>
</body>
</html>
Setting the on-event handlers property from JavaScript:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<h1>Lorem ipsum</h1>
<button>Print</button>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<h1>Lorem ipsum</h1>
<button>Print</button>
</body>
</html>
const button = document.querySelector('button');
button.onclick = function () {
window.print();
};
const button = document.querySelector('button');
button.onclick = function () {
window.print();
};
On-event handlers
- onclick
- onkeyup
- onload
- onchange
EventTarget
EventTarget.addEventListener()
Click (MouseEvent):
const button = document.querySelector('button#print');
button.addEventListener('click', function () {
window.print();
});
const button = document.querySelector('button#print');
button.addEventListener('click', function () {
window.print();
});
Keyup (KeyboardEvent, Key Values):
document.addEventListener('keyup', function (event) {
if (event.key == 'Enter') {
console.log('Enter key');
}
});
document.addEventListener('keyup', function (event) {
if (event.key == 'Enter') {
console.log('Enter key');
}
});