How to use JS to trigger a GIF animation? - javascript

I have an animated GIF that plays once (doesn't loop). I would like it to animate when clicked.
I tried something like this:
$('#plus').click(function(){
$('#plus').attr('src','');
$('#plus').attr('src','img/plus.gif')
});
With the hope that quickly resetting the src would trigger the animation, but no luck. Anyone know what would do it?

Try adding the image with a randomly generated querystring so it looks like a new image to the browser.
<script language="javascript" type="text/javascript">
function randomString() {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var string_length = 8;
var randomstring = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
}
document.randform.randomfield.value = randomstring;
}
$('#plus').click(function(){
$('#plus').attr('src','img/plus.gif?x=' + randomString())
});
</script>

function refreshSrc(who){
return who.src= who.src.split('?')[0]+'?='+(+new Date());
}
refreshSrc(document.images[0])
Tart it up with jQuery syntax, if you like.

This is a bit of an alternative approach.
You could export the individual frames as their own images and handle animation via javascript.
It lets you do a couple of cool things. A colleague recently had a little timer animation that was synced to the configurable slideshow interval in our image gallery.
The other thing you get out of this is you could use pngs and have translucent backgrounds.
There's probably a sprite animation library for javascript out there somewhere :)

Have you tried removing the img tag and adding it back again? (never tried it, just an idea)

You could try having a single-frame image (of the first frame of animation) and show/hide each one on click. If you want it to reset back to the single-frame image when the animation is done, you could use setTimeout (with how long the animation is as the length of time) and have it hide the animation and show the static image.

For those who want to do this when it scrolls into view i did the following.
Link for appear.js : https://github.com/morr/jquery.appear
$('img.large-magnify-glass-animation').appear(function() {
$(this).delay(200, function(){
$(this).attr('src','http://example.com/path/to/gif.gif');
});
});
I just loaded the same gif via the attr('src') upon visiblity after a short delay. No timestamp or random char function. Just used appear plugin.

Related

Jquery create animation swapping a series of images in a div

I am trying to create an effect where i display a short animation wherever the user clicks on a page. For this i need to quickly swap background image of a div with an array of image once. I couldn't find a way to do that just with the animate() or fadeOut() methods in jquery, so i tried it with setTimeout(), but all in vain. Please guide me to the best technique for what i am trying to do.
JSFiddle
P.S: I am having problems with including JSFiddle links in my posts, so i will leave it to others for edit. Although an explanation to this would help a lot.
This should work:
var imgc;
var images = Array("http://s11.postimg.org/8iznatxr3/image.png",
"http://s11.postimg.org/g08uq1na7/image.png",
"http://s11.postimg.org/hgkd86q73/image.png",
"http://s11.postimg.org/5fyx7gisf/image.png",
"http://s11.postimg.org/3pfw5z19b/image.png");
$(document).click(function(e){
imgc = -1;
$('#ball').show().css({left:e.pageX +'px',top:e.pageY+'px'});
setImage();
});
function setImage() {
imgc++;
var newimage = images[imgc];
if (imgc < 5) {
$('#ball').fadeOut(50).css("background-image", "url("+newimage+")").fadeIn(50);
setTimeout(setImage, 100);
}
}
JSFiddle
Note that I replaced animate() with fadeIn() and fadeOut().

animating one image tag with changing src attribute using jQuery

I have an application in which the one division contains a image that need to change in every three second. But the problem is that I also need to add some animations to that changing event. I have tried few things but those are not looking very pleasing. Is there any way I can use animate() on this? My code which just changes the images is as follows:
var arrayOfImages //asssume that this array have 10 images
var i = 0;
setInterval(function(){
$('.imageBox').attr('src', arrayImg[i]);
i++;
if(i == 10) i=0;
}, 3000);
Other then this I have tried fadeIn and fadeOut too, but this is also looking very naive.
var i = 0;
setInterval(function(){
$('.imageBox').fadeOut(500, function() {
$('.imageBox').attr("src",arrayImg[++i]);
$('.imageBox').fadeIn(500);
});
if(i == 10) i=0;
}, 3000);
Please any help on this is appreciable. Thank you in advance
this is link for fiddle http://jsfiddle.net/apf5X/8/
Have you tried jQuery Cycle 2?
It's a really powerful plugin with lots of animations. Not only for images but for any html tag!
It would probably be be easier to use a library.
Here are some suggestions to get you started:
http://flexslider.woothemes.com/
http://dimsemenov.com/plugins/royal-slider/
There are many more to choose from. A good keyword to search for would be javascript image slider or jquery image slider.

How to determine when a canvas has finished loading

So I was making a rather large canvas that was filled with 1x1 pixels, and I wanted to make a loading screen for it. The problem after the loop filling the canvas finishes, it alerts that it has finished loading, but the canvas has not actually changed. I made a jsfiddle here to demonstrate. How do I actually find out when the canvas has actually loaded using javascript or Jquery, and what is causing this behavior?
var ctx=document.getElementById('canvas').getContext('2d');
for(var x=1;x<600;x++){
for(var y=1;y<600;y++){
var color= '#' + Math.floor (Math.random() * 16777215).toString(16);
ctx.fillStyle=color;
ctx.fillRect(x,y,1,1);
}
}
alert('done!');
Since you said jquery was ok, just fire a custom event when the loops are done looping.
Any code that needs the canvas fully loaded can go in the event handler.
// Listen for custom CanvasOnLoad event
$(document).on( "CanvasOnLoad", canvasOnLoadHandler );
var ctx=document.getElementById('canvas').getContext('2d');
for(var x=1;x<600;x++){
for(var y=1;y<600;y++){
var color= '#' + Math.floor (Math.random() * 16777215).toString(16);
ctx.fillStyle=color;
ctx.fillRect(x,y,1,1);
}
// fire CanvasOnLoad when the looping is done
if(x>=599){
$.event.trigger({
type: "CanvasOnLoad"
});
}
}
console.log("...follows the for loops.");
// handle CanvasOnLoad knowing your canvas has fully drawn
function canvasOnLoadHandler(){
console.log("canvas is loaded");
}
It is just like a load-progress animation. Updating/advancing that animation from a running function usually doesn't work right away (screen updates when that function finishes).
Your canvas-code is (automatically) wrapped in a onload function: window.onload=function(){ /*your code here*/ };.
The last line of that function is alert('done!');, so naturally you'll get the alertbox before the screen updates and you see the noize.
One solution is to first one set and display's a loading-image, then using a setTimeOut (say 30ms) one renders the canvas, ending that canvas-function with another setTimeOut to remove the loading-image again.
Note: as you probably know, your code will generate (a lot of) hex-colors like #3df5 and #5d8a6, both of which aren't valid colors! Also you used 16777215, but Math.random() needs to be multiplied by 16777216. To fix this, you might want to try:
color='#'+((Math.random()+1)*16777216|0).toString(16).substr(1);
Here is some good read about random colors.
See this JSFiddle result as an example.
Hope this helps.

delay images for display purposes not efficiency using javascript?

I have run into numerous sites that use a delay in loading images one after the other and am wondering how to do the same.
So i have a portfolio page with a number of images 3 rows of 4, what i want to happen is for the page to load,except for the images in img tags. Once the page has loaded i want images 1 of each row to load then say 0.5 seconds later the next image in the row(s) and so no. I'm going to have a loading gif in each image box prior to the actual image being displayed.
I know its doable but cant seem to find the term for doing this. This is purely for looks as it is a design site.
Thanks for the help.
This is very easy to do in jQuery
$('img').each(function(i) {
$(this).delay((i + 1) * 500).fadeIn();
});
Fiddle: http://jsfiddle.net/garreh/Svs7p/3
For fading in rows one after the other in a table it just means changing the selector slightly. Remember to change from div to img -- I just used div for testing
$('tr').each(function(i) {
$('td div', this).delay((i + 1) * 500).fadeIn();
});
Fiddle: http://jsfiddle.net/garreh/2Fg8S/
Here is what you can do, you can load the image tags with out the src and using a custom property:
<img alt='The image' path='image/path.jpg' />
then you can use javascript to load the images when the site is loaded or whenever you please;
// simplified
window.onload = function () {
var images = document.getElementsByTagName('img');
// loop and assign the correct
for (var i =0; i < images.length;i++){
var path = images[i].getAttribute('path');
images[i].src = path;
}
}
I hope you get the concept of how the images are delayed
**please note the path attribute is not a standard one.
The easiest way I can think to do this is to have a table set up that will eventually hold the image tags, but have none on load. Javascript can loop through an array of image urls, and insert those image tags into random locations on the table.
If you want to have the delay, setInterval is the perfect tool. http://www.w3schools.com/jsref/met_win_setinterval.asp
// You can hard-code your image url's here, or better still, write
// a server-side script that will read a directory and return them
// so it is fully dynamic and you can add images without changing code
unpickedImages = array();
// Start loading
loadAllImages = setInterval( insertImage, 600 );
function insertImage() {
if( unpickedImages.length > 0 ) {
var imageUrl = unpickedImages.shift();
// pick empty x, y on your table
// Insert the image tag im that <td></td>
} else {
clearInterval( loadAllImages );
}
}
You really don't need javascript to do this. If you specify the image sizes in the HTML or CSS, the browser will layout and display the page while loading the images, which will likely be loaded in parallel. It will then display them as soon as it can.
That way if users re-visit your site and have the images cached, they all show up immediately. If you have a script to load the images after a delay, you are making visitors wait for content unnecessarily and all their efforts to have a faster browser and pay for a fast internet connection has gone to waste.

javascript : simple delayed image show

I'm trying to write a simple javascript snippet which delays the image loading by a certain number of millisecs below.
<html>
<head>
<script type="text/javascript">
function SetTimer()
{
var Timer = setInterval("showImage()",3000);
}
function showImage()
{
document.getElementById('showImage').style.visibility = 'visible';
}
</script>
</head>
<body onLoad="SetTimer()" style="visibility:hidden">
<div id=showImage>
<img src="gwyneth_paltrow_2.jpg">
</div>
</body>
</html>
Am I approaching this incorrectly?
thanks in advance
This is basically an OK approach.
There are some bugs, namely:
document.getElementByID('showImage')style.visibility = 'hidden';
getElementByID should be getElementById
needs a dot after ('showImage')
You are setting the visibility to 'hidden' in order to show it. Instead, you should start out as hidden, and then make it appear instead of disappear.
document.getElementById('showImage').style.visibility = 'hidden';
Well, the code is backwards given the stated goal of delaying the appearance of the image. If I just use your code as a basis, then I would have the visibility of the image as hidden, using CSS, and then trigger the display to visible on the timer.
However, having said that... This doesn't delay the loading of the image, it merely delays the display of it. The other way to handle it is to use the timer to load an Image object in Javascript and then insert it into the DOM. This, then, will actually delay the loading of the image for 3 seconds. Something like this:
function showImage()
{
var myImage = new Image();
myImage.src = "gwyneth_paltrow_2.jpg";
document.getElementById("showImage").appendChild(myImage);
}
I'm doing that from memory, so syntax may not be entirely correct.

Categories