简体   繁体   中英

$(window).on('hashchange') Not firing when I change the hash with Jquery programmatically?

I have two Jquery functions one is

$('.navbar-nav').on('click', 'a', function (event) {
    event.preventDefault(); //prevents quick jumps.
    var href = $.attr(this, 'href');
    href = href.replace(/^\//, '');
    if (href != '#') {
        if ($(href).length) {
            var g = $(href).offset().top - h;
            $bod.animate({
                scrollTop: g - 5
            }, 1000,
            function () { //change hash here
                if (history.pushState) {
                    history.pushState(null, null, href);
                }
                else {
                    window.location.hash = href;
                }
            });
        }
    };
    var g = $(window).width();
    if (g <= 768) {
        $(".navbar-toggle").click();
    }
});

And the second function is

$(window).on('hashchange', function() {
    alert(location.hash);
});

The hash change event does not alert. I am guessing that i might not be using event.preventdefault() properly. I am new to Jquery and cannot understand why hashchange is not triggered. Any ideas?

Edit: this code is wrapped in $(document).ready() & var $bod = $('html,body'); can this be the reason? Edit: The console does not present any Jquery errors.

As far as I know 'hashchange' is not a native jQuery event. It doesn't work for me either with jQuery. Just using regular JS works fine however, ie:

window.addEventListener('hashchange', function() {
    // DO STUFF
}, false);

And window.attachEvent... for older versions of IE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM