I have a Bootstrap site with a collapsed navbar in the mobile view. It works fine except that when the drop-down navbar menu is open and the user presses the back key on his mobile device, it stays although the browser does go back to the last page. So how can I collapse the drop-down navbar menu (if open) when the back button is pressed? I tried the following but it doesn't do anything:
$(window).on("navigate", function (event, data) {
var direction = data.state.direction;
if (direction == 'back') {
var opened = $('.navbar-collapse').hasClass('collapse in');
if ( opened === true ) { $('.navbar-collapse').collapse('hide'); }
}
});
Do note that I have already included the latest full version of JQuery Mobile (1.4.5) on my page. I even tried replacing the code inside the second if()
block with a simple alert()
but even that doesn't work so it seems the if()
block isn't even triggering. Not sure if it's even catching the event. Is there another way to accomplish this?
NOTE: To ensure Clayton's comment doesn't mislead visitors with a potential answer, this question is NOT a duplicate for two reasons:
- The problem described in my question is on Chrome Android and not Safari iOS, and
- The question he claims to be related is about navigation issues where pressing the back button isn't taking the user back to the previous page, whereas my question is about a drop-down sub-menu which isn't collapsing when the back button is pressed. My page navigations are working fine.