I would like to place a "please wait, loading" spinning circle animation on my site. How should I accomplish this using jQuery?
相关问题
- How to fix IE ClearType + jQuery opacity problem i
- jQuery add and remove delay
- Include empty value fields in jQuery .serialize()
- Disable Browser onUnload on certain links?
- how to get selected text from iframe with javascri
If you are using Turbolinks With Rails this is my solution:
This is the CoffeeScript
This is the SASS CSS based on the first excellent answer from Jonathan Sampson
As far as the actual loading image, check out this site for a bunch of options.
As far as displaying a DIV with this image when a request begins, you have a few choices:
A) Manually show and hide the image:
B) Use ajaxStart and ajaxComplete:
Using this the element will show/hide for any request. Could be good or bad, depending on the need.
C) Use individual callbacks for a particular request:
jQuery provides event hooks for when AJAX requests start and end. You can hook into these to show your loader.
For example, create the following div:
Set it to
display: none
in your stylesheets. You can style it whatever way you want to. You can generate a nice loading image at Ajaxload.info, if you want to.Then, you can use something like the following to make it be shown automatically when sending Ajax requests:
Simply add this Javascript block to the end of your page before closing your body tag or wherever you see fit.
Now, whenever you send Ajax requests, the
#spinner
div will be shown. When the request is complete, it'll be hidden again.You can grab an animated GIF of a spinning circle from Ajaxload - stick that somewhere in your website file heirarchy. Then you just need to add an HTML element with the correct code, and remove it when you're done. This is fairly simple:
You then just need to use these methods in your AJAX call:
This has a few caveats: first of all, if you have two or more places the loading image can be shown, you're going to need to kep track of how many calls are running at once somehow, and only hide when they're all done. This can be done using a simple counter, which should work for almost all cases.
Secondly, this will only hide the loading image on a successful AJAX call. To handle the error states, you'll need to look into
$.ajax
, which is more complex than$.load
,$.get
and the like, but a lot more flexible too.This would make the buttons disappear, then an animation of "loading" would appear in their place and finally just display a success message.
With all due respect to other posts, you have here a very simple solution, using CSS3 and jQuery, without using any further external resources nor files.