Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute document.ready even if user came to the page by hitting the back button

Tags:

jquery

I have a PHP page with jQuery's $(document).ready() which does some changes to the form on the page. This works fine. But if I come to this page and then went to another and then hit 'Back' from the browser and came back to this page, the $(document).ready() function does not seem to run at all. This is happening on FF as well as Chrome.

Is there some way I can have document.ready executed even if the user hit the browser's back button to come to my page?

like image 507
walmik Avatar asked Aug 08 '12 18:08

walmik


People also ask

What is $( document ready () function Why should you use it?

The ready() method is used to make a function available after the document is loaded. Whatever code you write inside the $(document ). ready() method will run once the page DOM is ready to execute JavaScript code.

Where is the document ready function?

So technically it doesn't matter where you put it. Many people like putting script in the head, because it makes sure the script is read before the page is loaded. Other people like putting it at the very end (just before the end body tag) so that all of the elements of the page are loaded before the script reads them.

Where do you put the document ready in HTML?

The function can be whatever you like - whatever you put inside the function will run when the document is ready (i.e. when the webpage is called by the browser). You don't need to insert it at the bottom of the HTML page - you can do it anywhere. People only insert it at the bottom to optimize their loading speed.

Can we use document ready in partial view?

yes you are allowed to have multiple $(document). ready() in a page just make sure you have included jquery file before calling this function.


1 Answers

I had exactly the same problem; @Alfabravo's link helped me a lot here: https://stackoverflow.com/a/12648785/679240

The code below worked okay enough for me, since what I actually needed was to do some cleanup either when the user entered the page or when the page was reached through the back button:

$(window).on('pageshow', function(){
    console.info('Entered the page!');
});

If you need to specifically detect specifically when the page was reached through the back button but not when entering it the first time, you may need to control a bit of state; the link above may help you there.

like image 97
Haroldo_OK Avatar answered Sep 30 '22 02:09

Haroldo_OK