5

I want to show a loading gif when a user is loading away from the page. I do this when it is loading like this:

CSS:

.no-js #loader { display: none;  }
.js #loader { display: block; position: absolute; left: 100px; top: 0; }
.se-pre-con {
position: fixed;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
z-index: 9999;
background: url(https://i.imgur.com/Bpa5eIP.gif) center no-repeat #fff;
}

JavaScript:

<script>
$(window).load(function() {
     Animate loader off screen
    $(".se-pre-con").fadeOut("slow");;
});
</script>

HTML:

<div class="se-pre-con"></div>

I could do this by adding .onClick to each link on the page but that would take time and I want to know if there is a easier way to show the gif upon loading away from the page.

  • You can use an iframe and keep the graphic while the new content loads, it would be much more accurate. I know that iframes are deprecated but it's good enough for google so I think it's good enough here. – www139 Nov 18 '15 at 00:07
  • 4
    _“but that would take time”_ – yes, a fraction of a millisecond … `$('a').on('click', …)` or `$('body').on('click', 'a', …)` – CBroe Nov 18 '15 at 00:07
  • use `unload` or rather `beforeunload` events just as you did with load. – godzsa Nov 18 '15 at 00:19

2 Answers2

4

Watch unload event or beforeunload event just as you do with load!

For example:

$(window).on("unload",function() {
     //your animation here
});

Also you can add a delay or something so the animation can end before leaving the page:

var triggered = false;    
$(window).on("unload",function(event) {
    if (triggered === true) {
        return; //this is run automatically after the timeout
    }

    event.preventDefault();
    // your animation here

    triggered = true; // set flag
    setTimeout(function(){$(this).trigger('unload');},1000); //set animation length as timeout
 });

I used this question for my solution: How to trigger an event after using event.preventDefault()

Community
  • 1
  • 1
godzsa
  • 2,105
  • 4
  • 34
  • 56
0

try using this

$(document).ajaxStart(function() {

  $("#loading").show();
});

$(document).ajaxComplete(function() {
$("#loading").hide();
});
});

CSS

.wait {
  top: 100px;
  z-index: 2000;
  height: 100%;
  width: 100%;
  vertical-align: bottom;
  position: relative;
}
.loader {
  background-position: center center;
  z-index: 1000;
  height: auto;
  width: 100%;
  position: absolute;
}
.loaderimg {
  height: 100%;
  width: 100%;
}

HTML

<div id="loading" class="loader">
  <h2 class="text-center wait">Loading results, please be patient</h2>
  <img class="loaderimg" src="img/scr_01.gif" />
</div>
centam
  • 1
  • 1
  • I dont think you understand. I currently have a loading image but I also want to show a loading out image. –  Nov 18 '15 at 03:28