سؤال

I just updated to chrome version 32.0.1700.76 m and I am now noticing that hashchange seem to act weird. sometimes it work, sometimes it doesn't.

I have the following code on my homepage and I haven't changed the code in a few months. worked fine a few days ago(before I updated to latest chrome version):

$(window).on('hashchange', function () {
    var page = location.hash.slice(1);

    $('[data-page]').addClass('hidden');

    $('[data-page=' + page + ']').css('z-index', '0');
    $('#1st-row').children().eq(0).css('z-index', '1');
    $('#1st-row').children().eq(1).css('margin-left', '-200px');    
    $('[data-page=' + page + ']').removeClass('hidden');

    $('#1st-row').children().eq(1).animate(
        { 'margin-left':'0px' }, 1000);

    $(':checkbox').checkbox('check');
    $('#debug').attr('value', 'true');
});

I figured something wasn't working as it should when I redesigned my site so i changed it a bit:

$(window).on('hashchange', function () {
    var page = location.hash.slice(1);

    $('[data-page=' + page + ']').slideDown();
});

but it's still not working. I have to reload the page several times, go to the site again(ctrl+l -> enter), reload a few more times and then it magically works. it won't work a second time though... I have to refresh and reload the page/site a few more times before it decides to let hashchange work.

you can test it at lingonsorbet.se. just add #advanced to the url and a box should appear to the right. works fine in firefox and ie.

am I doing something wrong or has anyone else run into this too?

هل كانت مفيدة؟

المحلول

hashchange is not fired on page load

The hashchange event is only triggered when you manually change the hash or when you click an in-page anchor link (<a href="#advanced">Advanced</a>). Reloading a page without changing the hash does not trigger hashchange.

You should refactor your hash-checking code into a new function and execute it

  1. on the hashchange event
  2. on page load.

Consider this code:

function changeLayoutByHash() {
    var page = location.hash.slice(1);
    $('[data-page=' + page + ']').slideDown();
    // etc.
}

$(window).bind('hashchange', changeLayoutByHash );

$(window).ready( changeLayoutByHash );

As per your question, I don't see inconsistencies in the way Chrome handles this.

If you keep reloading example.com#advanced, hashchange will not be fired. Only when you change the hash to example.com#advance (delete a character), it's registered as a changed hash.

Debugging

To find out whether or not certain events are being fired, you can always write a little console.log('hashchange fired'); into your event handlers and then (with ChromeDev Tools open) see in the console what your program does.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top