gif animation play only once onclick and mousedown - javascript

I have two images: static and animated. I am trying to play that animated image but only once. After that, it will change to static one.
My Code:
$(document).ready(function () {
$('#targetDIV_three').bind('click mousedown', function () {
srcToGif2 = "http://demo.pink-squid.co.uk/christmas/s3.gif";
$("#divthree_three").attr('src', srcToGif2);
});
});
Fiddle : http://jsfiddle.net/squidraj/33Sqd/
Currently, it is not stopping after the first animation.
Latest fiddle with single animated loop gif.
http://jsfiddle.net/squidraj/4rC8D/1/
Now can't see the animation though the img src is changing.

If you want this animated GIF to be played only once, modify it in Photoshop. Go to Window > Timeline, then select looping options (bottom left corner):
Save for web as GIF and voila!

Working Fiddle
Try This:
$(document).ready(function () {
$('#targetDIV_three').bind('click mousedown', function () {
[].slice.apply(document.images).filter(is_gif_image).map(freeze_gif);
function is_gif_image(i) {
return /^(?!data:).*\.gif/i.test(i.src);
}
function freeze_gif(i) {
var c = document.createElement('canvas');
var w = c.width = i.width;
var h = c.height = i.height;
c.getContext('2d').drawImage(i, 0, 0, w, h);
try {
i.src = c.toDataURL("image/gif"); // if possible, retain all css aspects
} catch(e) { // cross-domain -- mimic original with all its tag attributes
for (var j = 0, a; a = i.attributes[j]; j++)
c.setAttribute(a.name, a.value);
i.parentNode.replaceChild(c, i);
}
}
});
});
For getting desired effect you can setTimeout to trigger click event #targetDIV_three

Chnage your code to this. A timeout is set to set the old gif again.
$(document).ready(function () {
$('#targetDIV_three').bind('click mousedown', function () {
srcToGif2 = "http://demo.pink-squid.co.uk/christmas/s3.gif";
$("#divthree_three").attr('src', srcToGif2);
setTimeout(function(){
$("#divthree_three").attr('src', "http://demo.pink-squid.co.uk/christmas/s3_bg.gif");
},900);
});
});
http://jsfiddle.net/33Sqd/2/

Related

Resize Image on addeventlistener function

I'm trying to resize an image using addEventListener. I searched for this question and found similar ones but I haven't been able to make the function work properly.
The following code demonstrates a working function that resizes the image.
header.onload=function(){
var fullHeaderWidth=this.width
if(fullHeaderWidth>window.innerWidth)
header.width=window.innerWidth;
setInterval(function(){
if(fullHeaderWidth>window.innerWidth)
header.width=window.innerWidth;
else
header.width=fullHeaderWidth;
},50)
};
But when I try to use this function...
var header=new Image();
header=document.getElementById('header');
header.onload=function(){
var fullHeaderWidth=this.width
if(fullHeaderWidth>window.innerWidth)
header.width=window.innerWidth;
};
header.src='file:///C|/Users/Dillon/Development/Jesses Works/header.gif'
window.addEventListener('resize',function(){
if(fullHeaderWidth>window.innerWidth)
header.width=window.innerWidth;
else
header.width=fullHeaderWidth;
},false)
The event fires (I know this because I used alert in the function), but the image will not resize. Any ideas?
You're getting confused, I think you're trying to do something like this:
window.addEventListener('load', function () {
setInterval(function () {
var fullHeaderWidth = this.width;
if (fullHeaderWidth > window.innerWidth) {
header.width = window.innerWidth;
} else {
header.width = fullHeaderWidth;
}
}, 50);
});

Load Image and Fade In, but in sequential way

I'm trying to load my images and fade in. Its working. But lets suppose that I have 4 images. Right now, my script its working by loading the last image, not the first. How can I make my js load the first image, and just start loading the second after the first has been loaded?
Here's my code:
$(function(){
$("a").click(function(){
$("#load").load('load.html', function() {
$('#load img').hide();
alert($("#load img").length);
$('#load img').each( function(){
$(this).on('load', function () {
$(this).fadeIn();
});
});
});
return false;
});
});
See http://jsfiddle.net/5uNGR/15/
Try something where you are not trying to perform a fadeIn on each image as they load, but test the ok-ness of the next image in your animation queue each time ANY load event happens, then on the animation callback, see if the next one is ready. Here is a script that should work.
BTW, see http://www.sajithmr.me/javascript-check-an-image-is-loaded-or-not for more on image readiness testing.
$(function () {
// util fn to test if image loaded properly
var isImgLoadOk = function (img) {
if (!img.complete) { return false; }
if (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) {
return false;
}
return true;
};
$("a").on('click', function () {
$("#load").load('load.html', function () {
var imgs = $('#load img').hide(), //create image array and hide (chaining)
animIndex = 0, //position in the animation queue
isFading = false; //track state of whether an animation is in prog
// this is a load handler AND is called in the fadeIn callback if
// not at last image in the collection
var fadeNextImg = function () {
// make sure a load event didn't happen in the middle of an animation
if (isFading) return;
// last image in animation queue?
var isLast = animIndex == imgs.length - 1;
// get the raw image out of the collection and test if it is loaded happily
var targetImage = imgs[animIndex];
if (isImgLoadOk(targetImage)) {
// jQuery-up the htmlImage
targetImage = $(targetImage);
// increment the queue
animIndex++;
// set animation state - this will ignore load events
isFading = true;
// fade in the img
targetImage.fadeIn('slow', function () {
isFading = false;
// test to see if next image is ready to load by
// recursively calling the parent fn
if (!isLast) fadeNextImg();
});
}
};
imgs.on('load', fadeNextImg);
});
return false;
});
});
Ron's solution is a little over-engineered IMO. If your intention is indeed to load all of the images before the animation starts, then you could do something similar to the following:
$(function(){
$("a").click(function(){
$("#load").load('load.html', function() {
$('#load img').hide(); // I would recommend using css to hide the image instead
alert($("#load img").length);
$("#load img").each(function(i, image) {
setTimeout(function() { // For each image, set increasingly large timeout before fadeIn
$(this).fadeIn();
}, 2000 * i);
});
});
return false;
});
});

jquery plugin imgpreload

I have asked this question couple times, but non of the suggestions seems to be working.
I am using jstree plugin to build the tree. Based on the node_id, I am trying to load images to some divs. It kinda works but, I am having sporadic image display issues. Sometimes, I have to double click, sometimes single click shows the images.
I tried this:
img1 = new Image;
img1.src="teamA.png";
img2 = new Image;
img2.src="teamB.png";
img1.onload = function()
{
$("#div1").html(img1;
}
etc, but this is not working. I still see sporadicly images are now showing up on the divs.
I started looking at jquery plugin imgpreload as this:
$.imgpreload(['img1','img2', 'img3','img4','img5','img6'],
{
each: function() {
$(this).data('loaded')
$("#div1").html(img1);
}
});
this does not seem to be working either, any ideas or points?
I have done this:
$(function () {
var myImage1 = new Image();
$(img1)
.load(function () {
});
.attr('src', 'teamA.png');
});
getting syntax errors. Does this seem ok to you?
* updated * I modified the code as this:
$(function () {
var myImage1 = new Image();
$(myImage1).load(function ()
{
})
.attr('src', 'teamA.png');
alert(myImage1.width);
$('#div1').html("myImage1").css({"border": "0", "background": "white"});
}
Right after the load function, I am doing a:
alert(myImage.width) to see the size of the image, it is coming back at 0, so this does not seem to be working. There is definetely image.
update v2
$(function () {
var myImage1 = new Image();
$(myImage1).load(function ()
{
alert(myImage1.width);
$('#div1').html("myImage1").css({"border": "0", "background": "white"});
})
.attr('src', 'teamA.png');
});
ok, this code works assuming that the image is there. But I like to do is if the image is not there, I like to hide that div. I have this code, but it is not working on load event. How can I hide the divs that are empty?
$(function ()
{
var myImage1 = new Image();
$(myImage1).load(function ()
{
var image1Check = myImage1.width;
if (image1Check == 0 || image1Check < 30)
{
$('#div').html("").css("border", "");
}
else
{
$("#div1").html(myImage1).css("border","1px solid");
}
})
.attr('src', teamA.png);
});
Bind the load event before setting the src, and to handle a missing image, use .error()
$(function () {
var myImage1 = new Image();
$(myImage1).load(function () {
$("#div1").html(myImage1).css("border","1px solid");
}).attr('src', "teamA.png").error(function(){
$('#div1').html("").css("border", "");
});
});
You have to use $(this).data('loaded') in an if:
each: function() {
if ($(this).data('loaded')) {
// do something
}
},

Using Pixastic and .live with a class of images

I'm using the Pixastic plugin in JavaScript. I have a table filled with images that are blurred. When I go over them with the mouse I want them to get normal. And when the mouse leaves an image I want it to blur back. For some reason my code doesn't work. Here's the code:
Before, I copied the wrong code part, and I apologize for that this one is the one I'm asking about.
<script type="text/javascript">
$(document).ready(function(){
$('.photography').live('mouseover mouseout', function(event) {
if (event.type == 'mouseover') {
function () {Pixastic.revert('this');};
}
else {
function(){Pixastic.process('this', "blurfast", {amount:0.5});};
}
});
});
</script>
OK, so I managed to find my old code that actually works half way (when I hover over the image for the first time it works, but when I try for the second time it doesn't).
$(document).ready(function(){
var blur = function() {Pixastic.process(this, "blurfast", {amount:0.5});};
var unblur = function () {Pixastic.revert(this);};
$('.photography').each(blur);
$('.photography').hover(unblur,blur);
});
OK, so now I'm also adding the code for the function called revert:
revert : function(img) {
if (Pixastic.Client.hasCanvas()) {
if (img.tagName.toLowerCase() == "canvas" && img.__pixastic_org_image) {
img.width = img.__pixastic_org_width;
img.height = img.__pixastic_org_height;
img.getContext("2d").drawImage(img.__pixastic_org_image, 0, 0);
if (img.parentNode && img.parentNode.replaceChild) {
img.parentNode.replaceChild(img.__pixastic_org_image, img);;
}
return img;
}
}
else
if (Pixastic.Client.isIE()) {
if (typeof img.__pixastic_org_style != "undefined")
img.style.cssText = img.__pixastic_org_style;
}
}
So yesterday my friend discovered how this could be done ... the problem was that the plugin converts images into canvas anyway her's the code :
$(document).ready(function(){
$('.pic').each(function(){
this.onmouseout = function(){
var canvas1 = Pixastic.process(this, "blurfast", {amount:0.5});
canvas1.onmouseover = function(){
Pixastic.revert(this);
}
}
this.onload = function(){
var canvas = Pixastic.process(this, "blurfast", {amount:0.5});
canvas.onmouseover = function(){
Pixastic.revert(this);
}
}
});
});
Try doing this
$('.photography').live('mouseenter', function(event){
Pixastic.revert(this);
}).live('mouseleave', function(event){
Pixastic.process(this, "blurfast", {amount:0.5});
});

Javascript "while hovered" loop

Can anybody help me on this one...I have a button which when is hovered, triggers an action. But I'd like it to repeat it for as long as the button is hovered.
I'd appreciate any solution, be it in jquery or pure javascript - here is how my code looks at this moment (in jquery):
var scrollingposition = 0;
$('#button').hover(function(){
++scrollingposition;
$('#object').css("right", scrollingposition);
});
Now how can i put this into some kind of while loop, so that #object is moving px by px for as #button is hovered, not just when the mouse enters it?
OK... another stab at the answer:
$('myselector').each(function () {
var hovered = false;
var loop = window.setInterval(function () {
if (hovered) {
// ...
}
}, 250);
$(this).hover(
function () {
hovered = true;
},
function () {
hovered = false;
}
);
});
The 250 means the task repeats every quarter of a second. You can decrease this number to make it faster or increase it to make it slower.
Nathan's answer is a good start, but you should also use window.clearInterval when the mouse leaves the element (mouseleave event) to cancel the repeated action which was set up using setInterval(), because this way the "loop" is running only when the mouse pointer enters the element (mouseover event).
Here is a sample code:
function doSomethingRepeatedly(){
// do this repeatedly when hovering the element
}
var intervalId;
$(document).ready(function () {
$('#myelement').hover(function () {
var intervalDelay = 10;
// call doSomethingRepeatedly() function repeatedly with 10ms delay between the function calls
intervalId = setInterval(doSomethingRepeatedly, intervalDelay);
}, function () {
// cancel calling doSomethingRepeatedly() function repeatedly
clearInterval(intervalId);
});
});
I created a sample code on jsFiddle which demonstrates how to scroll the background-image of an element left-to-right and then backwards on hover with the code shown above:
http://jsfiddle.net/Sk8erPeter/HLT3J/15/
If its an animation you can "stop" an animation half way through. So it looks like you're moving something to the left so you could do:
var maxScroll = 9999;
$('#button').hover(
function(){ $('#object').animate({ "right":maxScroll+"px" }, 10000); },
function(){ $('#object').stop(); } );
var buttonHovered = false;
$('#button').hover(function () {
buttonHovered = true;
while (buttonHovered) {
...
}
},
function () {
buttonHovered = false;
});
If you want to do this for multiple objects, it might be better to make it a bit more object oriented than a global variable though.
Edit:
Think the best way of dealing with multiple objects is to put it in an .each() block:
$('myselector').each(function () {
var hovered = false;
$(this).hover(function () {
hovered = true;
while (hovered) {
...
}
},
function () {
hovered = false;
});
});
Edit2:
Or you could do it by adding a class:
$('selector').hover(function () {
$(this).addClass('hovered');
while ($(this).hasClass('hovered')) {
...
}
}, function () {
$(this).removeClass('hovered');
});
var scrollingposition = 0;
$('#button').hover(function(){
var $this = $(this);
var $obj = $("#object");
while ( $this.is(":hover") ) {
scrollingposition += 1;
$obj.css("right", scrollingposition);
}
});

Categories