'$(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.
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | anderssonma |
