Showing an image from an array of images - Javascript - 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>
}
}

Related

Randomize images when refreshing page js html

Here is a code that should render images randomly using DIV HTML rather than document.write, does anyone have an idea?
<script>
var theImages = new Array()
//Random-loading images
theImages[0] = '/img/pirc/hostnger-he.png' // replace with names of images
theImages[1] = '/img/pirc/hostnger-en.png' // replace with names of images
var j = 0
var p = theImages.length;
var preBuffer = new Array()
for (i = 0; i < p; i++){
preBuffer[i] = new Image()
preBuffer[i].src = theImages[i]
}
var whichImage = Math.round(Math.random()*(p-1));
function showImage(){
if(whichImage==0){
$('.hostnger').html('<img class="hostnger" src="'+theImages[whichImage]+'">')
}
else if(whichImage==1){
$('.hostnger').html('<img class="hostnger" src="'+theImages[whichImage]+'">')
}
}
</script>
<div class="hostnger"></div>
Randomize images when refreshing the pageenter code here
Where are you actually calling the showImage function?
You should add
showImage();
somewhere.
Are you including jQuery?
$('.hostnger')
Is a jQuery call and you are not including jQuery anywhere.

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">

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];
}
}

Accessing functions from within a Javascript Object (Javascript)

I am attempting to create a basic Hangman program. It's an array of tags which are assigned into an array of Objects (called Buttons). Each image is an image of a letter, so for example you would press the 'L' button, it would check whether this was in an WordArray (which is an array of chars), then it would act accordingly (to hide the letter, then update the gallows image if it needed to).
I cannot get the onclick method of the images to access the checkinarray function. What am i doing wrong?
var LetterAmount = 3; //make this 26. checked.
var WordArray = new Array();
var Buttons = new Array();
function checkinarray(num){
var z = 0;
while (z<4){
document.write("looping through word now");
if (num == WordArray[z]){
document.write("<br/>it is in the word");
}
z++;
}
}
function ButtonClicked(){
this.Image.src = "images/blank.jpg";
checkinarray(this.Number);
}
function Button(Image, Number) {
this.Image = Image;
this.Number = Number;
this.ButtonClicked = ButtonClicked;
}
function initialiseletters(){
var x;
//set up empty img tags for use
for(i = 0; i < LetterAmount; i++) {
document.write("<img id=" + i + ">");
}
for(x = 0; x < LetterAmount; x++) {
document.images[x].src = "images/" + x + ".jpg";
document.getElementById(x).onclick =function(){
Buttons[this.id].ButtonClicked();
}
Buttons[x] = new Button(document.images[x], "" + x);
}
}
function initialiseword(){
//WordArray = new Array();
WordArray[0] = 0;
WordArray[1] = 1;
WordArray[2] = 2;
WordArray[3] = 3;
}
function initialise(){
initialiseword();
initialiseletters();
document.write("testing overall");
}
I'm not seeing a problem with ButtonClicked calling checkinarray, but I'm seeing a problem with checkinarray -- it's calling document.write after the page rendering is complete (e.g., when the user clicks), which won't work. You need to modify the DOM via DOM methods (this will be made much easier if you use a toolkit like Prototype, jQuery, MooTools, Dojo, the Closure Library, YUI, etc.).
document.getElementById(x).onclick =function(){
Buttons[this.id].ButtonClicked();
}
Is where your problem is. 'this.id' is undefined.
document.write is not a good way to add elements to the DOM... Try document.createElement('img');
Then you already have reference to the image like so:
var img = document.createElement('img');
img.onclick = function()
{
//your click...
}
//add it to the view stack
document.body.appendChild(img);

Categories

Resources