javascriptajaxfragment-identifier

How to detect if URL has changed after hash in JavaScript


How can I check if a URL has changed in JavaScript? For example, websites like GitHub, which use AJAX, will append page information after a # symbol to create a unique URL without reloading the page. What is the best way to detect if this URL changes?


Solution

  • In modern browsers (IE8+, FF3.6+, Chrome), you can just listen to the hashchange event on window.

    In some old browsers, you need a timer that continually checks location.hash. If you're using jQuery, there is a plugin that does exactly that.

    Example

    Below I undo any URL change, to keep just the scrolling:

    <script type="text/javascript">
      if (window.history) {
        var myOldUrl = window.location.href;
        window.addEventListener('hashchange', function(){
          window.history.pushState({}, null, myOldUrl);
        });
      }
    </script>
    

    Note that above used history-API is available in Chrome, Safari, Firefox 4+, and Internet Explorer 10pp4+