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="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script type="text/javascript">
        window.onhashchange = function (ev) {
            console.log('new: ' + ev.newURL);
            console.log('old: ' + ev.oldURL);
        };
    </script>
</head>
<body>
    <div>
        <div>
            <a href="#div1">go to div1</a>
        </div>
        <div>
            <a href="#div2">go to div2</a>
        </div>  
    </div>

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

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: