แอตทริบิวต์เหตุการณ์ HTML onhashchange ถูกทริกเกอร์เมื่อมีการเปลี่ยนแปลงในส่วนจุดยึดของ URL ในเอกสาร HTML
ไวยากรณ์
ต่อไปนี้เป็นไวยากรณ์ -
<tagname onhashchange=”script”></tagname>
ให้เราดูตัวอย่างของแอตทริบิวต์เหตุการณ์ HTML onhashchange−
ตัวอย่าง
<!DOCTYPE html>
<html>
<head>
<style>
body {
color: #000;
height: 100vh;
background-color: #FBAB7E;
background-image: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%);
text-align: center;
}
.btn {
background: #db133a;
border: none;
color: #fff;
height: 2rem;
padding: 8px 10px;
}
</style>
</head>
<body onhashchange="hashChange()">
<h1>HTML onhashchange Event Attribute Demo</h1>
<button class="btn" onclick="change()">Set Hash</button>
<p class="msg"></p>
<script>
function change() {
location.hash = "newHashPart";
document.querySelector('.msg').innerHTML = 'The hash part of the URL is: ' + location.hash;
}
function hashChange() {
document.body.style.background = 'lightblue';
}
</script>
</body>
</html> ผลลัพธ์

คลิกที่ “ตั้งค่าแฮช ” เพื่อตั้งค่าแฮชใหม่เป็น URL ปัจจุบัน และสังเกตว่าแอตทริบิวต์เหตุการณ์ onhashchange ทำงานอย่างไร:
