JavaScript to animate a smily face by given images - javascript

i'm a begginer with JavaScript, i have a question is like changing images every 2 seconds i used array for 12 images and for loop but it didnt work the way i wanted, the changing goes from image 1 to image 12 directly without moving through the whole 12.
this the my script
var images = new Array(11) , x=0;
images[0] = new Array();
images [0].src = "images/smile_01.gif";
images[1] = new Array();
images [1].src = "images/smile_02.gif";
images[2] = new Array();
images [2].src = "images/smile_03.gif";
images[3] = new Array();
images [3].src = "images/smile_04.gif";
images[4] = new Array();
images [4].src = "images/smile_05.gif";
images[5] = new Array();
images [5].src = "images/smile_06.gif";
images[6] = new Array();
images [6].src = "images/smile_07.gif";
images[7] = new Array();
images [7].src = "images/smile_08.gif";
images[8] = new Array();
images [8].src = "images/smile_09.gif";
images[9] = new Array();
images [9].src = "images/smile_10.gif";
images[10] = new Array();
images [10].src = "images/smile_11.gif";
images[11] = new Array();
images [11].src = "images/smile_12.gif";
function changeimage(){
setInterval( function ima(){
for ( x = 0 ; x <= images.length ; x++ ){
document.getElementById("imag").src= images[x].src;
}
},1000);
}
HTML:
</head>
<body>
<img id = "imag" src="images/smile_00.gif" onload = "changeimage()">
</body>
</html>

The way I would do it is to create an array of all source URLs like this:
var images = [
"images/smile_01.gif",
"images/smile_02.gif",
....
];
You could use a loop to do this:
var images = [];
for (var i = 1; i <= 12; i++) {
images.push("images/smile_" + i + ".gif");
}
Then get the image element from the DOM
var imag = document.getElementById("imag");
And then run a function which calls itself every 2 seconds, changes the image, and increases a counter
function changeImage(i) {
imag.src = images[i % images.length];
setTimeout(function() {
changeImage(i+1)
}, 2000);
};
changeImage(0);
Bonus: This begins at the first image again after the last has been shown
Also note that unless you preload the images, you will probably get white flashes at least the first time each image is shown.

Your entire loop happens inside setTinterval, however for animation become vsible, you need to place each iteration of the loop in setInterval,
also as pointed out in comments your array can be simplified;
var images = [
"images/smile_01.gif",
"images/smile_02.gif",
"images/smile_03.gif",
"images/smile_04.gif",
...
];
var i = 0,
image = document.getElementById("imag");
setInterval( function () {
if (i >= images.length) {
i = 0;
}
image.src = images[i];
i++;
},1000);

var images = new Array(11), x=0;
images[0] = "images/smile_01.gif";
images[1] = "images/smile_02.gif";
images[2] = "images/smile_03.gif";
images[3] = "images/smile_04.gif";
images[4] = "images/smile_05.gif";
images[5] = "images/smile_06.gif";
images[6] = "images/smile_07.gif";
images[7] = "images/smile_08.gif";
images[8] = "images/smile_09.gif";
images[9] = "images/smile_10.gif";
images[10] = "images/smile_11.gif";
images[11] = "images/smile_12.gif";
function changeimage(){
setInterval( function(){
document.getElementById("imag").src = images[x];
document.getElementById("imag").title = images[x];
x++;
if (x >= images.length)
{
x=0;
}
},1000);
}
<img id="imag" src="http://www.terrafloraonline.com/images/userfiles/images/flower01LOW.png" onload="changeimage()" title="start" />
You don't need the loop. setInterval itself is a loop. Every time interval is run (each second) it adds 1 to x. I've corrected your array. If you run this script you can hover your mouse over the image. You will see that the title of the image changes every second. In my example the first image is just a placeholder to make the onload work. If you're going to use this, only copy the code.

Related

Want a reverse button for my image Array using JavaScript

Hello I have just created the following JavaScript code for a next button which when clicked will show the next image in my array. However I now want to reverse this by creating a new function for a "Previous" button which goes back down the array rather than forward. This will be much more images than just the 3 example ones you see in this Array:
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = "Media//Gallery//img_1.jpg";
imgArray[1] = new Image();
imgArray[1].src = "Media//Gallery//img_2.jpg";
imgArray[2] = new Image();
imgArray[2].src = "Media//Gallery//img_3.jpg";
This is my Next buttons function. I just need to reverse it for the Previous button but not sure how.
function nextImage(event) {
var img = document.getElementById("largeImage");
for(var i = 0; i < imgArray.length;i++)
{
if(imgArray[i].src == img.src)
{
if(i === imgArray.length){
img.src = imgArray[0].src;
break;
}
img.src = imgArray[i+1].src;
break;
}
}
}
This is the div for the previous button:
<div class="imgNav" onclick="previousImage(this);" style="width:190px">
This is the image which I want to change when you press the button:
<img id="largeImage" src="Media//Gallery//Image_1.jpg" alt="Large Image" />
Thank you so vety much in advance!
This should do it
JavaScript
currentIndex = 0;
function changeImage(direction)
{
var index = currentIndex + direction;
if (index < 0)
{
index = 0; // or use imgArray.length to rotate round
}
if (index > imgArray.length)
{
index = imgArray.length; // or use 0 to rotate round
}
document.getElementById('largeImage').src = imgArray[index].src;
currentIndex = index;
}
Html Code
<div class="imgNav" onclick="changeImage(-1)" style="width:190px">
<div class="OtherimgNav" onclick="changeImage(1)" style="width:190px">

Image swapping hyperlinks

I want to have some hyperlink images that keep changing after a period of time..I have used 2 arrays images and links..2 respective functions execute that change image and links respectively after 2 seconds of time..But I am getting a blank screen as output..I wrote the code as:
<html>
<head>
<title> New Document </title>
</head>
<body>
<img id="img" width="1300" height="200"/>
<link id="link" >
<script type="text/javascript">
var x=0;
var y=0;
var images = new Array();
var links = new Array();
images[0] = "D:\images\31.jpg";
images[1] = "D:\images\32.jpg";
links[0] = "https://www.google.co.in" ;
links[1] = "https://www.facebook.com" ;
function changeImage()
{
document.getElementById("img").src=images[x];
x = (x + 1) % images.length;
}
function changeLinks()
{
document.getElementById("link").href=links[y];
y = (y + 1) % links.length;
}
window.onload = function() {
changeImage();
setInterval(changeImage,2000);
}
window.onload = function() {
changeLinks();
setInterval(changeLinks,2000);
}
</script>
</body>
</html>
Your problem is this:
images[0] = "D:\images\31.jpg";
images[1] = "D:\images\32.jpg";
those are supposed to be hyperlinks, not file paths! Also, the backslash is an escape char in JS, so you need to double it (\\). So try something like:
images[0] = "file:/D:/images/31.jpg";
images[1] = "file:/D:/images/32.jpg";

Why can't i access the x variable of the bitmap? (javascript)

I'm trying to loop through 3 images in my array and add it to the stage (using easelJS). I want to position it as well. When I try to access the images in the array i get an error saying that the I can't set x of undefined. Why can't the x variable of the easeljs Bitmap be accessed?
function displayPosters() {
getPosters(); //get all images and assign it to designated array
console.log(frontPosters);
console.log(frontPosters.length);
if(currentCat == Category.HOME) { //if current category is HOME
for(var i = 0; i < frontPosters.length; i++) { //loop through posters
frontPosters[i].x = 40; //set x position for testing, also where error occurs
stage.addChild(frontPosters[i]); //add poster to stage
}
}
}
here is the code for loading and pushing those images into the frontPosters arrray.
var frontPosters = new Array(3);
function getPosters() {
var games = new Image(); //create 3 images
var apps = new Image();
var aboutme = new Image();
games.onload = function() { //add image to frontImages array on load
var gamesPost = new createjs.Bitmap(games);
frontPosters[0] = gamesPost;
};
apps.onload = function() {
var appPost = new createjs.Bitmap(apps);
frontPosters[1] = appPost;
};
aboutme.onload = function() {
var amPost = new createjs.Bitmap(aboutme);
frontPosters[2] = amPost;
};
games.src = "images/assets/posters/games_poster.jpg";
apps.src = "images/assets/posters/apps_poster.jpg";
aboutme.src = "images/assets/posters/aboutme_poster.jpg";
}
Using for(poster in frontPosters) is bad practice, because you're actually iterating over the Array Object and not the values (a.k.a. the Array itself). Use for(var i=0; i<frontPosters.length; i++) instead. It's the easiest solution, IMO.
for(var i = 0; i < frontPosters.length; i++) { //loop through posters
frontPosters[i].x = 40; //set x position for testing, also where error occurs
stage.addChild(frontPosters[i]); //add poster to stage
}
Edit
I think you are dealing with a race-condition. You are going over your array before all images were loaded. By setting var frontPosters = new Array(3); you automatically set three values to undefined which are pushed into the new array.
You should check that all images were loaded before proceeding with the script.
Here's an idea for you. Set a callback that will run only after the third image was loaded.
var frontPosters = new Array(3);
function getPosters(callback) {
var games = new Image(),
apps = new Image(),
aboutme = new Image(),
loaded = 0;
games.onload = function() {
frontPosters[0] = new createjs.Bitmap(this);
if (++loaded === 3) callback();
};
apps.onload = function() {
frontPosters[1] = new createjs.Bitmap(this);
if (++loaded === 3) callback();
};
aboutme.onload = function() {
frontPosters[2] = new createjs.Bitmap(this);
if (++loaded === 3) callback();
};
games.src = "images/assets/posters/games_poster.jpg";
apps.src = "images/assets/posters/apps_poster.jpg";
aboutme.src = "images/assets/posters/aboutme_poster.jpg";
}
function displayPosters() {
getPosters(function() {
if(currentCat == Category.HOME) { //if current category is HOME
for(var i = 0; i < frontPosters.length; i++) { //loop through posters
frontPosters[i].x = 40; //set x position for testing, also where error occurs
stage.addChild(frontPosters[i]); //add poster to stage
}
}
}); //get all images and assign it to designated array, only after all images were loaded
}

How to check if the image is loaded?

with ajax i get an array of pictures URL and then I need to create from them the gallery. I also need to make a counter that shows the number of downloaded images, it looks like this:
var images;
var load_image = new Image();
load_image.onload = function(){
myPhotoSwipe.show(0);
}
$.each(images['images'], function(key, value) {
load_image.src = ('index.php?load_image=' + value);
$('#image_count').remove();
$('span[class="loading"]').after('<div id="count"><h6>Images: ['+key+' / '+images_array['images'].length+']</h6></div>');
images+= '<li><img src="index.php?load_image='+value+'" /></li>';
});
The problem is that the counter is always loaded at penultimate element and stay there until all images are loaded, but I need to show the load of each like a progress.
P.S.
I also tried complete, but it didn't help.
This should fix it. The reason is because the load handler was being bound to only 1 image object.
var images;
$.each(images['images'], function(key, value) {
var load_image = new Image();
load_image.src = ('index.php?load_image=' + value);
$('#image_count').remove();
$('span[class="loading"]').after('<div id="count"><h6>Images: ['+key+' / '+images_array['images'].length+']</h6></div>');
images+= '<li><img src="index.php?load_image='+value+'" /></li>';
load_image.onload = function(){
myPhotoSwipe.show(0);
}
});
You are almost there.
The problem is that you are re-using the same image object. You need to create an array of load_image instances and increment your counter inside onload, when each of them returns.
function load(){
var imageUrls = [];
imageUrls.push('http://www.nasa.gov/images/content/690106main_iss033e005644_full.jpg');
imageUrls.push('http://www.nasa.gov/images/content/690669main_201209210010_full.jpg');
imageUrls.push('http://www.nasa.gov/images/content/691806main_hs3_full_full.jpg');
imageUrls.push('http://www.nasa.gov/images/content/689231main_Webb_Mirror_Cans_orig_full.jpg');
var images = [];
var i;
var counter = 0;
var mainDiv = document.getElementById('somediv');
var counterDiv = document.getElementById('counter');
for (i = 0; i < imageUrls.length; i++)
{
images[i] = new Image();
images[i].width = 100;
images[i].height = 100;
images[i].onload = function () {
counter++;
counterDiv.innerText = counter;
}
mainDiv.appendChild(images[i]);
images[i].src = imageUrls[i];
}
}

Showing an image from an array of images - Javascript

I have a large image which is shown on my homepage, and when the user clicks the "next_img" button the large image on the homepage should change to the next image in the array.
However, the next arrow when clicked does nothing, and the main image on the homepage does not change.
I need to do this in javascript.
In the HTML:
<!--Main Content of the page -->
<div id="splash">
<img src="images/img/Splash_image1.jpg" alt="" id="mainImg">
</div>
<div id="imglist">
<img src="images/next_img.png" alt="">
And then in the javascript file:
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = 'images/img/Splash_image1.jpg';
imgArray[1] = new Image();
imgArray[1].src = 'images/img/Splash_image2.jpg';
imgArray[2] = new Image();
imgArray[2].src = 'images/img/Splash_image3.jpg';
imgArray[3] = new Image();
imgArray[3].src = 'images/img/Splash_image4.jpg';
imgArray[4] = new Image();
imgArray[4].src = 'images/img/Splash_image5.jpg';
imgArray[5] = new Image();
imgArray[5].src = 'images/img/Splash_image6.jpg';
/*------------------------------------*/
function nextImage(element)
{
var img = document.getElementById(element);
for(var i = 0;i<imgArray.length;i++)
{
if(imgArray[i] == img)
{
if(i == imgArray.length)
{
var j = 0;
document.getElementById(element).src = imgArray[j].src;
break;
}
else
var j = i + 1;
document.getElementById(element).src = imgArray[j].src;
break;
}
}
}
Any help would be appreciated. Thanks.
Just as Diodeus said, you're comparing an Image to a HTMLDomObject. Instead compare their .src attribute:
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = 'images/img/Splash_image1.jpg';
imgArray[1] = new Image();
imgArray[1].src = 'images/img/Splash_image2.jpg';
/* ... more images ... */
imgArray[5] = new Image();
imgArray[5].src = 'images/img/Splash_image6.jpg';
/*------------------------------------*/
function nextImage(element)
{
var img = document.getElementById(element);
for(var i = 0; i < imgArray.length;i++)
{
if(imgArray[i].src == img.src) // << check this
{
if(i === imgArray.length){
document.getElementById(element).src = imgArray[0].src;
break;
}
document.getElementById(element).src = imgArray[i+1].src;
break;
}
}
}
Here's a somewhat cleaner way of implementing this. This makes the following changes:
The code is DRYed up a bit to remove redundant and repeated code and strings.
The code is made more generic/reusable.
We make the cache into an object so it has a self-contained interface and there are fewer globals.
We compare .src attributes instead of DOM elements to make it work properly.
Code:
function imageCache(base, firstNum, lastNum) {
this.cache = [];
var img;
for (var i = firstNum; i <= lastnum; i++) {
img = new Image();
img.src = base + i + ".jpg";
this.cache.push(img);
}
}
imageCache.prototype.nextImage(id) {
var element = document.getElementById(id);
var targetSrc = element.src;
var cache = this.cache;
for (var i = 0; i < cache.length; i++) {
if (cache[i].src) === targetSrc) {
i++;
if (i >= cache.length) {
i = 0;
}
element.src = cache[i].src;
return;
}
}
}
// sample usage
var myCache = new imageCache('images/img/Splash_image', 1, 6);
myCache.nextImage("foo");
Some advantages of this more object oriented and DRYed approach:
You can add more images by just creating the images in the numeric sequences and changing one numeric value in the constructor rather than copying lots more lines of array declarations.
You can use this more than one place in your app by just creating more than one imageCache object.
You can change the base URL by changing one string rather than N strings.
The code size is smaller (because of the removal of repeated code).
The cache object could easily be extended to offer more capabilities such as first, last, skip, etc...
You could add centralize error handling in one place so if one image doesn't exist and doesn't load successfully, it's automatically removed from the cache.
You can reuse this in other web pages you develop by only change the arguments to the constructor and not actually changing the implementation code.
P.S. If you don't know what DRY stands for, it's "Don't Repeat Yourself" and basically means that you should never have many copies of similar looking code. Anytime you have that, it should be reduced somehow to a loop or function or something that removes the need for lots of similarly looking copies of code. The end result will be smaller, usually easier to maintain and often more reusable.
Also, when checking for the last image, you must compare with imgArray.length-1 because, for example, when array length is 2 then I will take the values 0 and 1, it won't reach the value 2, so you must compare with length-1 not with length, here is the fixed line:
if(i == imgArray.length-1)
This is a simple example and try to combine it with yours using some modifications. I prefer you set all the images in one array in order to make your code easier to read and shorter:
var myImage = document.getElementById("mainImage");
var imageArray = ["_images/image1.jpg","_images/image2.jpg","_images/image3.jpg",
"_images/image4.jpg","_images/image5.jpg","_images/image6.jpg"];
var imageIndex = 0;
function changeImage() {
myImage.setAttribute("src",imageArray[imageIndex]);
imageIndex = (imageIndex + 1) % imageArray.length;
}
setInterval(changeImage, 5000);
Here's your problem:
if(imgArray[i] == img)
You're comparing an array element to a DOM object.
<script type="text/javascript">
function bike()
{
var data=
["b1.jpg", "b2.jpg", "b3.jpg", "b4.jpg", "b5.jpg", "b6.jpg", "b7.jpg", "b8.jpg"];
var a;
for(a=0; a<data.length; a++)
{
document.write("<center><fieldset style='height:200px; float:left; border-radius:15px; border-width:6px;")<img src='"+data[a]+"' height='200px' width='300px'/></fieldset></center>
}
}

Categories

Resources