I am working on a Web CMS. When the user clicks on a link to move to a different page, or submits a form, I want a "please wait" animated GIF to show up in the top
This won't work for submit buttons. Once the user clicks "submit", the request has been posted to the server. Once that happens, the action has been performed. The best you could do in that case is stop the user from seeing the response of their action, however the action would still be performed.
Also, the only way to stop the user from navigating to another page once another request has been started would be to redirect the user back to the page they came from. In general, cancelling out of the request is just a plain Bad Idea™
For forms, another option would be to use AJAX for all form submissions. AJAX requests can be cancelled, so you could use this to your advantage, although it makes things more complicated and harder to deal with.
If you still want to go through with this, knowing the implications though, you can easily do this with a JavaScript framework like jQuery, YUI, Dojo, MooTools, ExtJS, or Closure.
Here is an example of how to do this in jQuery. As I mentioned, you can't stop a request once it has started without refreshing the page the user is on (to stop the current page load) so I have omitted that part from this example.
$().ready(function() {
function showLoading(){
$loadingOverlay = $('');
$loadingAnimation = $('Loading...');
$("body").prepend($loadingAnimation).prepend($loadingOverlay);
}
$("a[href]").click(showLoading);
$("form").submit(showLoading);
});
To add an animated gif in the loading box, replace the text "Loading..." with an tag pointing to the loading gif of your choice. A live demo of this can be seen here: http://jsbin.com/opadi
You'll need this CSS to go with the code above:
#loadingOverlay {
position: absolute;
top: 0px;
left: 0px;
height: 100%;
width: 100%;
z-index: 1000;
background: #000;
filter:alpha(opacity=50);
-moz-opacity:0.5;
-khtml-opacity: 0.5;
opacity: 0.5;
}
#loadingAnimation {
position: absolute;
top: 30%;
left: 50%;
z-index: 1001;
}