javascript - JQuery hashchange event - where to place? - Stack Overflow

admin2025-04-17  0

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

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
    });
});
Share asked Oct 24, 2016 at 6:41 Baloon1985Baloon1985 892 silver badges10 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

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')
    }
});
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744885047a272485.html

最新回复(0)