JQuery hashchange event - where to place?

javascript, jquery

Solution

You can trigger it manually like:

$(document).ready(function () {
    $(window).on('hashchange', function () {
        //do something
    }).trigger('hashchange');
});

Or you can do it like:

$(document).ready(function () {
    //attaching the event listener
    $(window).on('hashchange', function () {
        //do something
    });

    //manually tiggering it if we have hash part in URL
    if (window.location.hash) {
        $(window).trigger('hashchange')
    }
});

Problem

I am using JQuery hashchange event. ``` $(window).on('hashchange', function () { //do something }); ``` When my url contains a hash during first time load I understand that this needs to be triggered with `$(window).hashchange();` Can I place it inside document ready instead? ``` $(document).ready(function () { $(window).on('hashchange', function () { //do something }); }); ```

Original source