onhashchange Event

Definition and Usage

An onhashchange event occurs when the fragment identifier (starting with the '#' symbol) of the current URL changes.

For an example of what a fragment identifier is: Suppose the current URL is http://www.example.com/test.htm#part2 - The fragment identifier of this URL will be #part2.

To call this event, you can:

Example

Example 1

Execute JavaScript After the Anchor Part Changes

<body onhashchange="myFunction()">

Try It Yourself

Example 2

How to assign the "onhashchange" event to the window object:

window.onhashchange = myFunction;

Try It Yourself

Syntax

In HTML:

<element onhashchange="myScript">

Try It Yourself

In JavaScript:

object.onhashchange = function(){myScript};

Try It Yourself

In JavaScript, use the addEventListener() method:

object.addEventListener("hashchange", myScript);

Try It Yourself

Note:Internet Explorer 8 or earlier versions do not support addEventListener() Method.

Technical Details

Bubbling: Supported
Cancelable: Not Supported
Event Type: HashChangeEvent
Supported HTML Tags: <body>
DOM Version: Level 3 Events

Browser Support

The numbers in the table indicate the first browser version that fully supports this event.

Event Chrome IE Firefox Safari Opera
onhashchange 5.0 8.0 3.6 5.0 10.6