Cách đơn giản nhất
boolVal = !boolVal;
Ví dụ hoàn chỉnh
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Toggle Boolean</title>
<style>
body { font-family: 'Segoe UI', sans-serif; padding: 20px; text-align: center; }
.result { font-size: 48px; font-weight: bold; color: #6a1b9a; margin: 30px 0; font-family: monospace; }
.label { font-size: 18px; color: #555; margin-bottom: 10px; }
button { padding: 15px 30px; font-size: 18px; background: #1976d2; color: white; border: none; border-radius: 8px; cursor: pointer; }
button:hover { background: #1565c0; }
.true { color: #2e7d32; }
.false { color: #c62828; }
</style>
</head>
<body>
<h1>Toggle Boolean trong JavaScript</h1>
<div class="label">Giá trị hiện tại:</div>
<div class="result" id="result"></div>
<button id="btn">ĐẢO NGƯỢC (TOGGLE)</button>
<h3>Nhấn nút để đảo ngược giá trị boolean</h3>
<script>
const btnEle = document.getElementById('btn');
const resEle = document.getElementById('result');
let boolVal = true;
updateDisplay();
btnEle.addEventListener('click', () => {
boolVal = !boolVal; // TOGGLE
updateDisplay();
});
function updateDisplay() {
resEle.textContent = boolVal;
resEle.className = 'result ' + (boolVal ? 'true' : 'false');
}
</script>
</body>
</html>
Kết quả
Mỗi lần nhấn nút: true ↔ false (đổi màu xanh/đỏ)
Các cách khác
1. Toán tử XOR (Bitwise)
boolVal ^= true; // Tương đương !boolVal cho boolean
2. Hàm toggle tái sử dụng
function toggle(boolRef) {
return !boolRef;
}
// Hoặc mutate object
const state = { enabled: true };
function toggleState(obj, key) {
obj[key] = !obj[key];
}
toggleState(state, 'enabled');
3. Toggle class CSS (Phổ biến trong UI)
element.classList.toggle('active');
// Thêm class nếu chưa có, xóa nếu đã có
4. Toggle attribute
button.toggleAttribute('disabled');
input.toggleAttribute('readonly');
Ứng dụng thực tế
- Bật/tắt menu, modal, dropdown
- Play/Pause video, audio
- Dark/Light mode
- Enable/Disable nút submit
- Show/Hide password
// Ví dụ: Dark mode toggle
const toggleBtn = document.getElementById('darkModeToggle');
toggleBtn.addEventListener('click', () => {
document.body.classList.toggle('dark-mode');
localStorage.setItem('darkMode', document.body.classList.contains('dark-mode'));
});