play/stop gif on click using javascript - javascript

I want a gif to play when clicked, and to stop when clicked again. I'm following this method: http://www.hongkiat.com/blog/on-click-animated-gif/
So far, I have:
HTML
<figure>
<img src="test.png" alt="Static Image" data-alt="test.gif"/>
</figure>
<script src="playGif.js" type="text/javascript"></script>
playGif.js
(function($) {
// retrieve gif
var getGif = function() {
var gif = [];
$('img').each(function() {
var data = $(this).data('alt');
gif.push(data);
});
return gif;
}
var gif = getGif();
// pre-load gif
var image = [];
$.each(gif, function(index) {
image[index] = new Image();
image[index].src = gif[index];
});
// swap on click
$('figure').on('click', function() {
var $this = $(this),
$index = $this.index(),
$img = $this.children('img'),
$imgSrc = $img.attr('src'),
$imgAlt = $img.attr('data-alt'),
$imgExt = $imgAlt.split('.');
if($imgExt[1] === 'gif') {
$img.attr('src', $img.data('alt')).attr('data-alt', $imgSrc);
} else {
$img.attr('src', $imgAlt).attr('data-alt', $img.data('alt'));
}
});
})(jQuery);
Instead of swapping the content of src and data-alt, this only puts data-alt into src, and data-alt remains the same.
The gif does play on click, but if clicked again it reloads the gif instead of reverting to the png (at least in Chrome and Firefox. IE just does nothing on further clicks).

So here is the finished jsfiddle: https://jsfiddle.net/2060cm1c/
It is a simple variable swapping problem:
a=1;b=2;
a=b;// now a=2
b=a;// a=2, b=a=2
To solve it, you need a temporary variable:
a=1;b=2;
temp=a;a=b;
b=temp;
Now solve the OP's problem:
var temp=$img.attr('src');
$img.attr('src', $imgAlt).attr('data-alt', temp);
So, the problem is as easy as swapping 2 variables. You don't need the if to check the extension.

Related

Image array for javascript slideshow not appearing

I'm making a slideshow in javascript for a class assignment and I have the slideshow working but it's not displaying the images. I can see that the image icon changes but the actual image is not showing.
<script type="text/javascript">
//put images in array
var pics = new Array();
pics[0] = new Image();
pics[0].src = "images/forest.jpg";
pics[1] = new Image();
pics[1].src = "images/mountains.jpg";
pics[2] = new Image();
pics[2].src = "images/nature.jpg";
pics[3] = new Image();
pics[3].src = "images/snowtops.jpg";
var index = 0; //start point
var piclength = pics.length - 1;
function slideshow() {
document.slide.src = pics[index];
if (index < piclength) {
index++;
}
else {
index = 0;
}
}
function slide() {
setInterval(slideshow, 3000);
}
</script>
<body onload="slide()">
<h1>Nature Photography</h1>
<main>
<section>
<p>I am an enthusiastic about nature photography. Here is a slideshow of my
works.</p>
<aside> <img id="myImage" src="images/forest.jpg" name="slide" width="95%">
</aside>
First, I would put the script tag after your HTML. This will allow you to cache DOM elements without waiting for the "DOMContentLoaded" event or the "load" (window) event to be fired.
Second, you should cache the "myImage" element. Something like const slider = document.getElementById('myImage').
Third, check your console. Maybe your image URLs are wrong? And make sure your HTML is valid. From what you posted, you are missing a lot of things (doctype, html/head tags, you didn't close body tag and similar)

Automatically load an image using javascript

I'm using this code to build a gallery:
window.onload=function(){
var image = document.getElementsByClassName('thumbnails')[0].getElementsByTagName('img');
var mainImage = document.getElementById('rr_lrg_img');
[].forEach.call(image,function(x){
x.onmouseover = function(){
mainImage.src = x.src;
};
});
}
The code loads different thumbnails on the big image when "onmouseover". Now I would like to "preload" the first image from that gallery of thumbnails. I tried using onload with
rr_lrg_img.src=document.getElementsByClassName('thumbnails')[0].getElementsByTagName('img')[0].src
but then it conflicts with the onmouseover. Any ideas? I can only use javascript, no jquery.
Since your var image is actually a collection of images, you need to use the [0] index pointer to target the first one:
window.onload=function(){
var image = document.getElementsByClassName('thumbnails')[0].getElementsByTagName('img');
var mainImage = document.getElementById('rr_lrg_img');
mainImage.src = image[0].src; // Add this line (preload first image into main one)
function toMainImage() {
mainImage.src = this.src;
}
[].forEach.call(image,function(x){
x.addEventListener("mouseenter", toMainImage, false);
});
}
.thumbnails img{height:50px;}
<img src="//placehold.it/200x200&text=default" id="rr_lrg_img">
<div class="thumbnails">
<img src="//placehold.it/200x200/cf5&text=1">
<img src="//placehold.it/200x200/f0f&text=2">
<img src="//placehold.it/200x200/444&text=3">
</div>

Something goes wrong with fadeIn

Hello I want to fadeOut image, and then do fadeIn with a new one, so I wrote a simple code, but something goes wrong, because when .photo img fadesOut, then fadesIn this same photo, but after, a few second its changes because of new "src", but even if browser didn't load a new image, the old one shound't show, becuase src is changed, but it shows, and after a second, maybe two changes to the new one. Can somebody tell me what's wrong?
var dimage = $next.children("img").attr("rel");
$(".photo img").fadeOut("slow", function () {
$(".photo img").attr("src", dimage);
$(".photo img").fadeIn("slow");
});
This may be because the image has to load after the src is altered.
Consider putting the image in a tag, then setting the css property to display:none. This way the image will preload in the browser before your script runs and will be available when it does.
you aren't giving the new image enough time to load.
function loadImage (src) {
return $.Deferred(function(def){
var img = new Image();
img.onload = function(){
def.resolve(src);
}
img.src = src;
}).promise();
}
var dimage = $next.children("img").attr("rel");
var imageLoadedDef = loadImage(dimage);
$(".photo img").fadeOut("slow", function () {
def.done(function(src){
$(".photo img").attr("src", src);
$(".photo img").fadeIn("slow");
});
});
the problem as highlighted is about images not ready for display when you call them, so the solution is to preload them before starting the slideshow, create a function with an array of images path
function preLoad(){
var imgs = {'test1.jpg', 'test2.jpg', 'test3.jpg'};
var img = document.createElement('img');
for(var i = 0; i < imgs.leght; i++){
img.src = imgs[i]; //all images gets preloaded at this stage
}
startSlider(); //here you will do your code
}

JavaScript to change images

I have set of images named as img1, img2, img3, img4,......., imgx. So, I want to code a JavaScript to display an image img1 at document.onload() and on first click image to be changed to img2 next on second click the image to be changed at img3 and then same to the next image on every NEXT button click. In this manner I need even PREVIOUS button to go back to the previously viewed images.
How to implement this?
var currentImage = 1;
window.onload = function() {
showImage();
};
document.getElementById("next").onclick = function() {
currentImage++;
showImage();
}
function showImage() {
document.getElementById("image").src = "img" + currentImage + ".jpg";
}
These are the basics and should help you get started. If you need help implementing the rest, ask us what you want to do specificially and what you tried. Hint, you'll need to handle the case where there is no "next" image to show. Do you want it to come back to the beggining or just not work?
<script type="text/javascript">
var images = new Array("img/image1.jpg", "img/image2.jpg", "img/image3.jpg");
var cur_image = 0;
function goNextImage() {
var img = document.getElementById('image');
cur_image++;
if (cur_image == images.length) {
cur_image = 0;
}
img.src = images[cur_image];
}
</script>
<img src="img/image1.jpg" id="image" onclick="goNextImage()" />

Preloading Image Bug in IE6-8

Page in question: http://phwsinc.com/our-work/one-rincon-hill.asp
In IE6-8, when you click the left-most thumbnail in the gallery, the image never loads. If you click the thumbnail a second time, then it will load. I'm using jQuery, and here's my code that's powering the gallery:
$(document).ready(function() {
// PROJECT PHOTO GALLERY
var thumbs = $('.thumbs li a');
var photoWrapper = $('div.photoWrapper');
if (thumbs.length) {
thumbs.click( function(){
photoWrapper.addClass('loading');
var img_src = $(this).attr('href');
// The two lines below are what cause the bug in IE. They make the gallery run much faster in other browsers, though.
var new_img = new Image();
new_img.src = img_src;
var photo = $('#photo');
photo.fadeOut('slow', function() {
photo.attr('src', img_src);
photo.load(function() {
photoWrapper.removeClass('loading');
photo.fadeIn('slow');
});
});
return false;
});
}
});
A coworker told me that he's always had problems with the js Image() object, and advised me to just append an <img /> element inside of a div set to display:none;, but that's a little messy for my tastes--I liked using the Image() object, it kept things nice and clean, no unnecessary added HTML markup.
Any help would be appreciated. It still works without the image preloading, so if all else fails I'll just wrap the preloading in an if !($.browser.msie){ } and call it a day.
I see you've fixed this already, but I wanted to see if I could get the pre-loading to work in IE as well.
try changing this
photo.fadeOut('slow', function() {
photo.attr('src', img_src);
photo.load(function() {
photoWrapper.removeClass('loading');
photo.fadeIn('slow');
});
});
to this
photo.fadeOut('slow', function() {
photo.attr('src', img_src);
if (photo[0].complete){
photoWrapper.removeClass('loading');
photo.fadeIn('slow');
} else {
photo.load(function() {
photoWrapper.removeClass('loading');
photo.fadeIn('slow');
});
}
});

Categories