Karthikeyan Sankarababu Karthikeyan Sankarababu - 1 month ago 22
Javascript Question

JQuery hashchange event - where to place?

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
});
});

Answer

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')
    }
});
Comments