Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide loading gif when the browser back button is clicked?

I have a loading spinning animated .gif that appears while the page is loading after a form has been submitted, and everything works fine. However, if you submit the form, and then click on the back arrow on the browser, it shows the previous page, with the loading .gif still visible.

I have it set so that the loading gif is hidden when the page loads. But if you simply click the back button in a browser (like firefox), it doesn't fully reload the page and the animation gif is still visible.

Is there any way to hide the loading .gif when the browser back button is clicked?

Here's my jquery code:

<!-- inline scripts related to this page -->
<script type="text/javascript">
    // Show spinning animation on form submit.
    $("#filter-results-form").submit(function (e) {
        // Check for form errors before displaying loading gif.
        if ($('.field-validation-error').length > 1) {
            $("#loading-image").hide();
        } else {
            $("#loading-image").show(0); // show animation
        }
        return true; // allow regular form submission
    });
</script>

Here is my relevant html:

<div>
    <button type="submit"><i class="fa fa-search"></i> Search</button>
    <span class="loading collapse" id="loading-image"><img src="@Url.Content("~/content/img/layout/ajax-loader.gif")"></span>
</div>

And I have tried this as a solution, but it doesn't work:

jQuery(function ($) {
    $("#loading-image").hide(); // Hide animation on page load.
});
like image 233
Daniel Congrove Avatar asked Sep 14 '15 13:09

Daniel Congrove


2 Answers

I found this to work, without having to disable the cache. Turns out there is a pageshow event that lets you perform actions even when the page is loaded from cache.

Here's my solution code:

$(window).bind("pageshow", function(event) {
    $("#loading-image").hide();
});

Source: https://stackoverflow.com/a/12648745/1937348

like image 124
Daniel Congrove Avatar answered Nov 15 '22 18:11

Daniel Congrove


It happens because your browser is inserting in cache all elements including your page. When you go back, it loads the last state in cache.

If you want that your navigation loads from server and not from cache you need to declarate a meta-tag or a header within the server to prevent caching your pages.

Here you are examples:

HTML (meta tags)

 <meta http-equiv="Cache-control" content="no-cache">

PHP (header)

 header("Cache-Control: no-cache, must-revalidate"); //HTTP 1.1
 header("Pragma: no-cache"); //HTTP 1.0
 header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
like image 20
Marcos Pérez Gude Avatar answered Nov 15 '22 18:11

Marcos Pérez Gude