JavaScript onhashchange Event

You are Here:

JavaScript onhashchange Event

The onhashchange event occurs when the current URL changes to target a specific section within the page.

onhashchange Event as Attribute

Example

HTML Online Editor
<!DOCTYPE html> <html> <body onhashchange="myFunction()"> <h3 id="html">Learn HTML</h3> <h3 id="css">Learn CSS</h3> <h3 id="javascript">Learn Javascript</h3> <h3 id="jquery">Learn Jquery</h3> <h3 id="ajax">Learn AJAX</h3> <a href="#css">Move to CSS</a> <a href="#javascript">Move to Javascript</a> <a href="#html">Move to HTML</a> <script> function myFunction(){ alert("oldURL: "+event.oldURL+"\n\nnewURL: "+event.newURL); } </script> </body> </html>

Syntax

As Attribute

<element onhashchange = "JavaScript">

As Property

object.onhashchange = function(){ // code };

Using Event Listener

window.addEventListener("hashchange" , myScript);

onhashchange Event as Property

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <h3 id="html">Learn HTML</h3> <h3 id="css">Learn CSS</h3> <h3 id="javascript">Learn Javascript</h3> <h3 id="jquery">Learn Jquery</h3> <h3 id="ajax">Learn AJAX</h3> <a href="#css">Move to CSS</a> <a href="#javascript">Move to Javascript</a> <a href="#html">Move to HTML</a> <script> var x = document.getElementsByTagName("body")[0]; function myFunction(){ alert("oldURL: "+event.oldURL+"\n\nnewURL: "+event.newURL); } x.onhashchange = myFunction; </script> </body> </html>

Using addEventListener() Method

Note: The addEventListener() method is not supported in Internet Explorer 8 and below.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <h3 id="html">Learn HTML</h3> <h3 id="css">Learn CSS</h3> <h3 id="javascript">Learn Javascript</h3> <h3 id="jquery">Learn Jquery</h3> <h3 id="ajax">Learn AJAX</h3> <a href="#css">Move to CSS</a> <a href="#javascript">Move to Javascript</a> <a href="#html">Move to HTML</a> <script> function myFunction(){ alert("oldURL: "+event.oldURL+"\n\nnewURL: "+event.newURL); } window.addEventListener("hashchange", myFunction); </script> </body> </html>

Reminder

Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in JavaScript.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author