- The hashchange event is very useful to detect the changes in URL and helps in displaying custom content in the browser.
- hashchange event help in implementing a routing logic.
- In this demo,”We will implement hashchange event callback and render different content on browser”.
- The browser support for on hashchange event is as following screenshot taken from can i use online tool.
- we can attach callback function by window.onhashchange() or window.addEventListener(“hashchange”,callback).
- The following code contains the used of hashchange event where 2 hyperlinks are present #name and #subject that modifies the location hash value.
<!DOCTYPE html>
<html>
<head>
<title>hashchange event demo</title>
</head>
<body>
<h1 id="messageContainer"></h1>
<a href="#subject">subject</a>
<a href="#name">name</a>
<script>
var MyApp = {
handleHashChange : function(event){
var currentHash = location.hash,
message= document.getElementById("messageContainer");
if(currentHash === "#name"){
message.innerText ="Name: Sandeep";
}else if(currentHash === "#subject"){
message.innerText ="Name: Computer Science";
}
}
};
window.addEventListener("hashchange",MyApp.handleHashChange);
window.addEventListener("load",MyApp.handleHashChange);
</script>
</body>
</html>
- The output of above code when windows load with URL http://localhost:8080/MyApp/#name.
- when user pressed the subject link the hashchanged and callback gets executed and Computer Science is render in browser.
- The hashchange event object look like below screenshot.