Event onresize (หรือ resize) ทริกเกอร์เมื่อ ขนาด Browser Window เปลี่ยนแปลง ใช้ window.outerWidth/Height (ขนาด Browser ทั้งหมด) หรือ window.innerWidth/Height (ขนาด Viewport)
ตัวอย่างโค้ด
<!DOCTYPE html>
<html>
<head>
<script>
function resizeFunction() {
var val = "Window Width=" + window.outerWidth + ", Window Height=" + window.outerHeight;
document.getElementById("test").innerHTML = val;
}
</script>
</head>
<body onresize="resizeFunction()">
<p>Resize browser window and check the window (browser window) height and width again.</p>
<p id="test"></p>
</body>
</html>
คำอธิบาย Properties
| Property | ความหมาย |
|---|---|
window.outerWidth | ความกว้าง Browser ทั้งหมด (รวม Scrollbar, Border) |
window.outerHeight | ความสูง Browser ทั้งหมด |
window.innerWidth | ความกว้าง Viewport (พื้นที่แสดงเนื้อหา) |
window.innerHeight | ความสูง Viewport |
แนวทางปฏิบัติที่ดี (Best Practices)
- Debounce/Throttle: Resize ยิงบ่อยมาก ควรจำกัดความถี่
- ใช้ addEventListener: แทน Inline Handler
onresize - ResizeObserver API: สำหรับ Element Resize (ไม่ใช่ Window) — ทันสมัยกว่า
ตัวอย่าง Debounce
let resizeTimer;
window.addEventListener('resize', () => {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(() => {
console.log('Resized:', window.innerWidth, window.innerHeight);
// ทำงานที่นี่
}, 150); // รอ 150ms หลังหยุด Resize
});
ResizeObserver (Element Resize)
const resizeObserver = new ResizeObserver(entries => {
for (let entry of entries) {
console.log('Element size:', entry.contentRect.width, entry.contentRect.height);
}
});
resizeObserver.observe(document.querySelector('.my-element'));