I want to change an image when a checkbox is clicked. Until the new image is fully loaded a loader image should appear on top of the current image. While loading the opacity of the current image should also change to 0.5.
The function should therefore consist of the following steps:
On checkbox click:
While loading:
When new image is loaded:
How can this be done with jQuery?
Thanks in advance for all proposals!
The steps should actually be
on checkbox click, start to preload the new image
Start by creating an Image object, and then setting its load property to a function that will be called once the image has been completely loaded. Then ( after setting the load property ) set the src
attribute of the Image object we created to the Url of your image.
while waiting, set the opacity, show the loader
Opacity you can control with the css property opacity
. You should have the loader already in the page but hidden, and just show it while the preloading is in progress..
when preload is complete hide preloader, show image reset opacity
The function we defined for the load
attribute gets called and inside the handler we reset the opacity, hide the preloader and set the src
of our element in the page to the src
of the Image object we created..
here is a full example: http://www.jsfiddle.net/kqC9U/
Well, lets take a quick moment and dissect the problem:
If your changing the image source (which can be done almost instantly) why do you need a loader gif? In fact, displaying the loader gif takes as long as displaying the new image. If you'd like the loader gif for dramatic appeal you can display the loader.gif, wait 5 seconds, then change to the new image.
Changing the image can easily be accomplished by changing the src attribute on a current image. For instance,
$.('#myCheckboxID').change(function()
{
$.('#myPictureID').attr('src', "path/to/new/image/");
});
Let me know if you decide you need that loader gif for dramatic effect and I'll help you wire it up
edit: Because the loading effect is desired, try something like this. I'll pencil down some psuedocode, let me know if its not specific enough.
Change the source on your first picture
Hide the first picture for x seconds (get a feel for how long it takes to load)
Unhide a loading gif of the same size with opacity already set
hide the loading gif and unhide the first picture
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.