JavaScript hashchange Event

Created with Sketch.

JavaScript hashchange Event

Summary: in this tutorial, you will learn about the JavaScript hashchange event and how to handle it effectively.

Introduction to the JavaScript hashchange event

The URL hash is everything that follows the pound sign (#) in the URL. For example, suppose that you have the following URL:

https://python-tutorials.in/javascript-hashchange-event/#header

Code language: JavaScript (javascript)

The URL hash is header. If the URL hash changes to footer, like this:

https://python-tutorials.in/javascript-hashchange-event/#footer

Code language: JavaScript (javascript)

The hashchange event fires when the URL hash changes from one to another. In this example, it changes from #header to #footer.

To attach an event listener to the hashchange event, you call the addEventListener() method on the window object:

window.addEventListener('hashchange',() =>{
console.log('The URL has has changed');
});

Code language: JavaScript (javascript)

To get the current URL hash, you access the hash property of the location object:

window.addEventListener('hashchange',() => {
console.log(`The current URL hash is ${location.hash}`);
});

Code language: JavaScript (javascript)

Additionally, you can handle the hashchange event by assigning an event listener to the onhashchange property of the window object:

window.onhashchange = () => {
// handle hashchange event here
};

Code language: JavaScript (javascript)

Summary

  • The hashchange event fires when the URL hash changed.
  • To register an event listener, you call the addEventListener() method or assign an event listener to the onhashchange property of the window object.

Leave a Reply

Your email address will not be published. Required fields are marked *