My Technical Notes

Thursday, 8 October 2015

OnHashChange event

Below is an example in the use of `window.onhashchange` event:

<!DOCTYPE html>

<html lang="en" xmlns="">
    <meta charset="utf-8" />
    <script type="text/javascript">
        window.onhashchange = function (ev) {
            console.log('new: ' + ev.newURL);
            console.log('old: ' + ev.oldURL);
            <a href="#div1">go to div1</a>
            <a href="#div2">go to div2</a>

    <div id="div1" style="border: 1px solid red">
        div 1 content
    <div id="div2" style="border: 1px solid green">
        div 2 content

When you click on one of the anchor tags, the `onhashchange` event will fire and the console log messages will look like:

new: file:///C:/path/to/HTMLPage.html#div2
old: file:///C:/path/to/HTMLPage.html#div1

No comments: