Event onhashchange ทริกเกอร์เมื่อ Hash Fragment (ส่วนหลัง #) ของ URL เปลี่ยนแปลง ใช้สำหรับ SPA Routing, Deep Linking, In-page Navigation
ตัวอย่างโค้ด
<!DOCTYPE html>
<html>
<body onhashchange="newFunc()">
<button onclick="functionChange()">Click to change anchor</button>
<script>
function functionChange() {
location.hash = "about";
var hash = location.hash;
document.write("The anchor part is now: " + hash);
}
function newFunc() {
alert("Anchor part changed!");
}
</script>
</body>
</html>
คำอธิบาย
location.hash— อ่าน/ตั้งค่า Hash Fragment (รวม #)- Event ทริกเกอร์เมื่อ User คลิก Anchor Link (
<a href="#section">) หรือ JS เปลี่ยนlocation.hash - ไม่ Reload หน้า — เหมาะสำห SPA
รูปแบบมาตรฐานสมัยใหม่
window.addEventListener('hashchange', (e) => {
console.log('Old URL:', e.oldURL);
console.log('New URL:', e.newURL);
console.log('New Hash:', location.hash);
// Router Logic
const route = location.hash.slice(1) || 'home';
loadView(route);
});
การใช้งานจริง
- SPA Routing แบบง่าย: Hash-based Routing (
#/users/123) - Deep Linking: แชร์ Link ไป Section เฉพาะ
- Tab/Accordion State: Sync UI กับ URL Hash
- Analytics: Track Hash Navigation
Hash vs History API
| Feature | Hash Routing | History API |
|---|---|---|
| URL Format | #/path | /path (Clean) |
| Server Config | ไม่ต้อง Config | ต้อง Redirect ทุก Route → index.html |
| SEO | แย่กว่า | ดีกว่า |
| Browser Support | IE8+ | IE10+ |