Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preventDefault and override browser's back button behavior?

Tags:

javascript

Sorry if duplicate, but I don't understand how I can use the basic approach in my case. I need to hide some div, when user presses back button in browser. That is all what I need. The page must not to be reloaded. I tried this way:

window.onpopstate = function (event) {
    event.preventDefault();
    alert("Back button pressed");
    myDiv.style.display = 'none';
}

But this doesn't work at all. Even alert doesn't fire. And the browser goes back as always.

How to make it work? First of all this must works in mobile browsers. Will the using of window.location.hash trigger page reloading or not?

like image 969
splash27 Avatar asked Oct 29 '25 10:10

splash27


1 Answers

Short answer: You can't change it.

Long answer:

You should first set a State then get it with event handler.

So, simply, when user clicks on a specific section of your document, for example a <a>, you set a State then when he clicks on back button ( of browser ) you've got a fired event.

someElement.addEventListener( 'click', function( e ) {

    history.pushState({ state: 'someElement was clicked' }, 'title', 'some-element.html' );

})

Now, as back button pressed, you've got an alert ( as presented in your question ).

For furthur information check here: Manipulating the browser history( mdn )

like image 134
mrReiha Avatar answered Oct 30 '25 23:10

mrReiha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!