Event

HashChangeEvent

Creates a new HashChangeEvent fired when the fragment identifier of the URL has changed

Syntax

JavaScript
new HashChangeEvent(type, options?)

Parameters

ParameterTypeDescription
typestringThe type of event (hashchange)
optionsHashChangeEventInitOptions including oldURL and newURL

Return Value

A new HashChangeEvent object

Examples

Basic Usage
window.addEventListener('hashchange', (e: HashChangeEvent) => {
  console.log('Old URL:', e.oldURL)
  console.log('New URL:', e.newURL)
})
Practical Example
window.addEventListener('hashchange', () => {
  const hash = window.location.hash.slice(1)
  console.log('Current section:', hash)
  const section = document.getElementById(hash)
  section?.scrollIntoView({ behavior: 'smooth' })
})
Advanced Usage
function onRouteChange(callback: (route: string) => void) {
  window.addEventListener('hashchange', () => {
    callback(window.location.hash.slice(1))
  })
}

Understanding HashChangeEvent

The HashChangeEvent method in JavaScript creates a new HashChangeEvent fired when the fragment identifier of the URL has changed. It belongs to the Event object and is one of the most widely used methods for working with event values in modern JavaScript and TypeScript applications.

The method signature is new HashChangeEvent(type, options?). It accepts 2 parameters: type, options. When called, it returns a new hashchangeevent object. Understanding when and how to use HashChangeEvent() helps you write more expressive, readable code.

Common use cases for HashChangeEvent include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like event-popstateevent, event-addeventlistener, enabling you to chain operations together for complex data manipulation pipelines.

Browser support for HashChangeEvent is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.

Browser Compatibility

Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.

Related Methods

More Event Methods

Other methods in the Event object

Related Tools

More Event Methods

Explore JavaScript Methods

Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.