HTML onhashchange Event Attribute
HTML onhashchange Event Attribute works when there have been changes to the anchor part. The anchor part starts with the ‘#’ symbol of the current URL. It also enables the execution of a script or function on hash change and is used for dynamic web applications updating without full page reload. In order to trigger this event, we have a couple of options:
- Modify the anchor section by updating the (location.hash) or (location.href) attribute of the Location Object.
- Navigate to the current page with a distinct bookmark by using the “back” or “forward” buttons.
- Click a hyperlink leading to a bookmark anchor.
Supported Tag
This event attribute supports the <body> tag.
Syntax
<element onhashchange = "script">
Attribute Value
This attribute contains a single value script and it runs when onhashchange event attribute is triggered. This attribute is associated with <body> tag only.
Example 1: This example illustraates the implementation of the onhashchange Event Attribute.
html
<!DOCTYPE html> < html > < head > < title >onhashchange event attribute</ title > < style > body { text-align: center; } h1 { color: green; } </ style > </ head > < body > < h1 >GeeksforGeeks</ h1 > < h2 > onhashchange event attribute </ h2 > < button onclick = "changePart()" > Try it </ button > < div id = "gfg" ></ div > < script > function changePart() { location.hash = "2"; let geeks = "Anchor part: " + location.hash; document.getElementById("gfg").innerHTML = geeks; } function myFunction() { alert("The anchor part has changed!"); } </ script > </ body > </ html > |
Output:
Example 2: This is another example that illustraates the implementation of the onhashchange Event Attribute.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < style > body { font-family: Arial, sans-serif; margin: 20px; display: flex; justify-content: center; align-items: center; flex-direction: column; } h1 { color: green; } h2 { color: crimson; } button { margin: 5px; } #output { border: 1px solid #ccc; padding: 10px; margin-top: 10px; } </ style > </ head > < body > < h1 >GeeksforGeeks</ h1 > < h2 >onhashChange Example</ h2 > < button onclick = "changeHash('#section1')" > Change to Section 1 </ button > < button onclick = "changeHash('#section2')" > Change to Section 2' </ button > < div id = "output" > Current Hash: < span id = "currentHash" > No hash </ span > </ div > < script > function HashHandle() { document.getElementById("currentHash"). textContent = location.hash || "No hash"; } function changeHash(newHash) { location.hash = newHash; } window.onhashchange = HashHandle; HashHandle(); </ script > </ body > </ html > |
Output:
Supported Browsers
- Google Chrome 5 and above
- Edge 8 and above
- Firefox 3.6 and above
- Opera 10.6 and above
- Safari 5 and above