I’m developing a simple web quiz and using javascript, I would like to create an effect that displays a small image (1UP) that wanders around the “game deck” when users reach a specific level or score; user could gain an extra life simply clicking on it in time.
Do you know any Jquery plugin or javascript snippet to achieve an effect like this?
It’s actually surprisingly easy to do this:
Create the element:
Set its source:
Position it absolutely and such:
(Obviously, use whatever coordinates and size you want.)
You may want to make sure it appears above other things:
Add it to the document:
Move it around
Use
window.setInterval(orsetTimeoutdepending on how you want to do it) to move it around by changing itsstyle.leftandstyle.topsettings. You can useMath.randomto get a random floating point number between 0 and 1, and multiply that and run it throughMath.floorto get a whole number for changing your coordinates.Example
This creates an image at 50,50 and animates it (in a very jittery random way; I didn’t spend any time making it look nifty) every fifth of a second for 10 seconds, then removes it:
(I prefer re-scheduling on each iteration via
setTimeout[as above] to usingsetInterval, but it’s totally your call. If usingsetInterval, remember the interval handle [return value fromsetIntervaland usewindow.clearTimeoutto cancel it when you’re done.)The above is raw DOM/JavaScript; jQuery offers some helpers to make it a bit simpler, but as you can see, it’s pretty straightforward even without.