Lắng nghe sự kiện keydown trên document hoặc window. Kiểm tra event.key (khuyên dùng) hoặc event.keyCode (cũ): ArrowUp (38) tăng, ArrowDown (40) giảm.
Ví dụ
Biến a tăng/giảm khi nhấn phím mũi tên lên/xuống:
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Keyboard counter JS</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.result { font-size: 20px; font-weight: 500; color: green; }
</style>
</head>
<body>
<h1>Tăng/giảm biến bằng phím mũi tên</h1>
<div class="result">0</div>
<h3>Nhấn phím mũi tên LÊN/XUỐNG để tăng/giảm</h3>
<script>
const resEle = document.querySelector(".result");
let a = 0;
document.addEventListener("keydown", (e) => {
if (e.key === 'ArrowUp') resEle.textContent = ++a;
else if (e.key === 'ArrowDown') resEle.textContent = --a;
});
</script>
</body>
</html>
Kết quả
Số hiển thị tăng khi nhấn Up, giảm khi nhấn Down.
Lưu ý: Dùng e.key thay e.keyCode (deprecated). Thêm e.preventDefault() nếu không muốn cuộn trang.