Search code examples
javascriptmootools

History event is triggered on the page load with mootools


I have a problem with history management, with cpojer implementation (http://mootools.net/forge/p/history) on safari (all versions) and old versions of chrome the history change event is triggered on the page load, check the console message 'history change': http://codepen.io/anon/pen/ByNRyy

var history_url_handler = function(url){

    console.log('history change');

};

History.addEvent('change', history_url_handler);

There aren't problems with firefox and the latest versions of chrome, suggestions? Thanks


Solution

  • If I recall correctly this is probably a oddity/bug in old chrome (most probably webkit) where a page load triggers the onhashchange event.

    If I remember correctly, if you load the page giving an initial hash this should not trigger onhashchange but even if it does you can just check if the initial hash is the one you gave and discard the event callback in that case; providing you expect no hash on load a check like this should work:

       if (location.hash.trim() === '') return;
    

    You can also skip only the first callback by keeping a reference like this:

    var history_url_handler = (function(){ 
      var firstCall = true; 
      return function(url){
        if (firstCall && location.hash.trim() === '') return;
        firstCall = false;
        console.log('history change');
      };
    })()