Problems with random images in array - javascript

var eieren = 0;
var eieren = Math.floor((Math.random() * 4) + 1);
var imgArray = [ 'img/ei1.png' , 'img/ei2.png' , 'img/ei3.png', 'img/ei4.png' ];
imgArray.length;
var eiImg = imgArray[eieren - 1];
console.log( eiImg );
document.getElementsByTagName( 'img' )[0].src = eiImg;
document.getElementsByTagName( 'img' )[0].addEventListener( "click", changeImage );
var counter = eieren - 1;
function changeImage()
{
//Load new image if this is not the last image
if ( counter < imgArray.length - 1 )
{
document.getElementsByTagName( 'img' )[0].src = imgArray[ ++counter % imgArray.length];
}
};
<html lang="en">
<head>
<!-- <link rel="stylesheet" type="text/css" href="css/style.css">-->
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<img src="img/questionmark.png" id= "first" alt="questionmark" width="200" height= "300" onClick ="changeImage()">
<script type="text/javascript" src="js/eigame.js"></script>
</body>
</html>
I am new on this website and I'm having struggles with a project of mine. Let me explain what I want to make.
I have an array with 4 images. Every time the page refreshes, a random image (so a random image from the array) appears. I'm making a very simple game where you have to click on images of eggs with 1 crack, 2 cracks, 3 cracks and one where a chick is coming out of an egg. The goal of the game is to get all the chicks out of the eggs. So the page is refreshed and for example, the image with the egg with 2 cracks shows up. That means you have to click 2 times (array: img1(egg with 1 crack), img2(egg with 2 cracks), img3(egg with 3 cracks), img4(image with chick coming out the egg) to show the image with the chick out of the egg. At the end of the game (i still have to make a timer) all of the pictures have to be the chick coming out of the egg. So with I think with a For loop, it will check at the end of the game if all images are img4.
It's working a little bit, but there is a problem. When I refresh the page a random image shows up. For example img2. I have to click 2 times to get to the chick. But in my case, when i click, it changes first in to the first image of the array, img1. And then when you click it again it will go from img1 to 2 to 3 to 4 and if you click again to 1 again.
What I want is if the page for example shows img2, and you click on the image, it will go to the next image in the array. Not first go to img1 and then go to the next images.
Once that is fixed, I want the clickfunction to stop at the last image in the array. So if the last image in the array is shown, the chick out of the egg, you can't click anymore further. Now, when you click the chick picture, it goes back to the first image in the array.
Here is my code so far (I'm very new with javascript, I'm sorry for the many questions) I hope someone can help me with this, I've been stuck for days..
var eieren = 0;
var eieren = Math.floor((Math.random() * 4) + 1);
var imgArray = [ 'img/ei1.png' , 'img/ei2.png' , 'img/ei3.png', 'img/ei4.png' ];
imgArray.length;
var eiImg = imgArray[eieren - 1];
console.log(eiImg);
document.getElementsByTagName('img')[0].src = eiImg;
var counter=[0];
function changeImage(){
//Change image and increment counter
document.getElementById("first", "second").src=imgArray[counter++ % imgArray.length];
}
This is in my HTML:
<img src="img/questionmark.png" id= "first" alt="questionmark" width="200" height= "300" onClick ="changeImage()">
I made a Fiddle but it's not working on it. Gosh, I'm probably doing something wrong. Sorry!.. https://jsfiddle.net/mtjsd0bL/

I think that your problem is with counter++ in change image. Try set it to eiImg not to [0]
Something like this:
var eieren = 0;
var eieren = Math.floor((Math.random() * 4) + 1);
var imgArray = [ 'img/ei1.png' , 'img/ei2.png' , 'img/ei3.png', 'img/ei4.png' ];
imgArray.length;
var eiImg = imgArray[eieren - 1];
console.log( eiImg );
document.getElementsByTagName( 'img' )[0].src = eiImg;
document.getElementsByTagName( 'img' )[0].addEventListener( "click", changeImage );
var counter = eieren - 1;
function changeImage()
{
//Load new image if this is not the last image
if ( counter < imgArray.length - 1 )
{
document.getElementsByTagName( 'img' )[0].src = imgArray[ ++counter % imgArray.length];
}
}
Check my updated answer.

Related

Javascript image slideshow using a for loop

i'm trying to cycle through 3 images using a for loop in javascript. Here is my code:
<img name="slide" width="300" height="300">
var i=0;
var images = [];
images[0] = "images/1.jpg";
images[1] = "images/2.jpg";
images[2] = "images/3.jpg";
function changeImage () {
for(i=0; i < images.length; i++) {
document.slide.src = images[i];
}
}
window.onload = changeImage;
Currently, only image 3 is displayed. Anyone know what i'm doing wrong here?
Yes - this is because your for loop run finishes instantly so there's no time for slides 1 and 2 to be shown.
Give this a try:
var currentImage = 0,
images = [
"https://unsplash.it/200/300?image=100",
"https://unsplash.it/200/300?image=101",
"https://unsplash.it/200/300?image=102"
];
function initSlideshow() {
setImage(0);
setInterval(function(){
nextImage();
},1000);
}
function nextImage() {
if(images.length === currentImage + 1){
currentImage = 0;
} else {
currentImage++;
}
setImage(currentImage);
}
function setImage(image) {
document.querySelectorAll('.slide')[0].src = images[image];
}
window.onload = initSlideshow();
Example: https://jsfiddle.net/vvbdwazc/
Currently, only image 3 is displayed. Anyone know what i'm doing wrong
here?
it's all being displayed but the reason why you can only see the 3rd image is because you're not pausing for a certain time before displaying the next image hence it seems like it's not working.
use setInterval() method to show each image after a specified time.
Example:
var i=0;
var images = [];
images[0] = "images/1.jpg";
images[1] = "images/2.jpg";
images[2] = "images/3.jpg";
function changeImage () {
for(i=0; i < images.length; i++) {
document.slide.src = images[i];
}
}
var myVar = setInterval(function(){ changeImage() }, 1000);
You may later wish to prevent the setInterval() method from executing any longer in that case have a look at clearInterval().
window.onload = changeImage; tells me you want to change the image on page load event? In other words, the image changes only upon page load (or refresh).
Since state is not maintained by default (eg local storage or session storage or cookies) your best bet would be to use a random generator to choose randomly. See Generating random whole numbers in JavaScript in a specific range?
This is because the for works so fast it gets quickly to the third image. You could use instead some setInterval like this:
<img id="slide" width="300" height="300">
<script>
var images = [];
images[0] = "images/1.jpg";
images[1] = "images/2.jpg";
images[2] = "images/3.jpg";
var i = 0;
setInterval(function() {
var slide = document.querySelector("#slide"); //Select the img element by ID
slide.src = images[i++];
if(i > images.length - 1)
i = 0;
}, 1000); //Time in milliseconds
</script>
This will change constantly back to the first image when it reaches the last one.
Edit: Forgot to mention. setInterval works like a "repeater", it will work indefinitely until you clear it. To clear it you need to asign it to a variable and then use clearInterval passing the variable.
var interval = setInterval(function(){}, 1000) //example
clearInterval(interval);
Like so.

Javascript - New image on refresh for rotating gallery

I have set up a rotating gallery on a homepage using the Javascript code below. The gallery works great, except I would like to have a different image show on refresh. What do I need to change in the code to make this happen? Thank you!
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script>
$.fn.preload = function() {
this.each(function(){
$('<img/>')[0].src = this;
});
}
var images = Array(
"1.jpg",
"2.jpg",
"3.jpg",
"4.jpg",
"5.jpg",
"6.jpg",
"7.jpg",
"8.jpg"
);
$([images[0],images[1],images[2],images[3],images[4]]).preload();
// Usage:
var currimg = 0;
$(document).ready(function(){
function loadimg(){
$('#outerWrapper').animate({ opacity: 1 }, 400,function(){
//finished animating, minifade out and fade new back in
$('#outerWrapper').animate({ opacity: 0.7 }, 100,function(){
currimg++;
if(currimg > images.length-1){
currimg=0;
}
var newimage = images[currimg];
//swap out bg src
$('#outerWrapper').css("background-image", "url("+newimage+")");
//animate fully back in
$('#outerWrapper').animate({ opacity: 1 }, 600,function(){
//set timer for next
setTimeout(loadimg,5000);
});
});
});
}
setTimeout(loadimg,5000);
});
</script>
You can set currimg to a random value from 0 to n, where n is the total number of images in the gallery. Upon refresh, the currently displayed image will be inclined to be different from the one displayed prior to refresh.
currimg = Math.floor(Math.random()*8);

javascript setInterval / onload

I'm referring to the accepted answer for Change image in HTML page every few seconds. In this code, the very first timer event/image change occurs 6 secs after loading (then every 3 secs as expected). Could anyone explain to a beginner like me why this is so?
Thanks.
EDIT: Sorry for that, my fault. Let me try to explain what I'd like to do in the first place. The code given shows first startpicture.jpg and then cycles through image1.jpg to image3.jpg. I just want it to cycle through image1.jpg to image3.jpg without a seperate start picture (or all 4 pictures, including startpicture.jpg). Therefore is replaced startpicture.jpg with image1.jpg which made me get the wrong impression that the first image change occurred after 6 secs.
Maybe someone can help me how to change this code to cycling through the pictures without a designated start picture.
As per your edit, you can simply remove the startpicture (or replace with image1), and initially call the displayNextImage function immediately, then start the interval:
<!DOCTYPE html>
<html>
<head>
<title>change picture</title>
<script type = "text/javascript">
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.getElementById("img").src = images[x];
}
function displayPreviousImage() {
x = (x <= 0) ? images.length - 1 : x - 1;
document.getElementById("img").src = images[x];
}
function startTimer() {
//call immediately
displayNextImage();
//then start interval
setInterval(displayNextImage, 3000);
}
var images = [], x = -1;
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
</script>
</head>
<body onload = "startTimer()">
<img id="img" src="image1.jpg">
<button onclick="displayPreviousImage()">Previous</button>
<button onclick="displayNextImage()">Next</button>
</body>
</html>
may be its time taken to load the images ,
you can load all the image first and then start changing,
var images= new Array();
for(var i=0;i<imagelocation.length;i++)
{
images[i]=new Image();
images[i].onload=function(){ if(i=imagelocation.length){changeImage();}}
images[i].src=imagelocation[i]; //image location is array containg link
}
function changeImage()
{
//what u had written earlier
}

How to get JavaScript to rotate through a series if images

I'm having an issues where I cannot get my code to rotate multiple images in a cycle for my image gallery (just a bunch of images i got on google). I can however to get 1 image to cycle through the images but everything iv tried to get it to work with more than one has failed. Any help/ tips would be useful. Im in college for web development and i understand the basics of javascript it just seems when it comes to creating applications i have a bit of trouble.
Here is a link to my code: jsFiddle
$(document).ready(function () {
var img = document.images;
// Holds the image collection
var counter = 0;
var imgArray = [];
imgArray[0] = "http://www.zeroprox.tk/temp/images/img1.png";
imgArray[1] = "http://www.zeroprox.tk/temp/images/img2.jpg";
imgArray[2] = "http://www.zeroprox.tk/temp/images/img3.png";
imgArray[3] = "http://www.zeroprox.tk/temp/images/img4.jpg";
imgArray[4] = "http://www.zeroprox.tk/temp/images/img5.jpg";
imgArray[5] = "http://www.zeroprox.tk/temp/images/img6.png";
imgArray[6] = "http://www.zeroprox.tk/temp/images/img7.jpg";
imgArray[7] = "http://www.zeroprox.tk/temp/images/img8.png";
$("#left-arrow").click(function () {
if (counter < 0) {
counter = imgArray[counter] - 1;
} else {
counter--;
}
img[1].src = imgArray[counter];
});
// Left arrow... Previous
$("#right-arrow").click(function () {
counter = (counter + 1) % imgArray.length;
img[1].src = imgArray[counter];
});
// right arrow... Next
});
JSFiddle
Check this, it should solve your problem ;)
You were replacing every time the same image, now creates a new one and remove another.
Also added div#imagelist to use as a image container and access easier from JavaScript
var newImg = $(document.createElement("img"));
newImg.attr("src",imgArray[counter]);
$("#imagelist img").last().remove();
$("#imagelist").prepend(newImg);

using onmouseover as

I have a continuous loop of alternating images that I would like to be able to interrupt and have display a new picture that corresponds with the current displayed picture using an onmouseover affect for as long as the mouse is on the image.
As an example to better describe my problem, I would like to have a bunch of images alternating on the screen every five seconds (which I can already do). Then when the mouseover event happens, have the images stop alternating and have a new image displayed that corresponds with the image that was just displayed (it will be another image that describes the image that was just being displayed). I also want the images to stop alternating while the mouse is over the images.
So far I can get the first image to display its corresponding image, but I can't seem to get the rest to work. Also I can't get the alternating images to stop while the mouse is still on the image.
Here's what I have so far:
<body>
<img src="image1.jpeg" alt="Image1" width="344" height="311" id="rotator" onmouseover="this.src='imageText1.jpeg'" onmouseout="this.src='image1.jpeg'">
<script type="text/javascript">
(function() {
var rotator = document.getElementById("rotator");
var imageDir = '';
var delayInSeconds = 5;
var images = ["image2.png", "image3.gif", "image4.png", "image5.jpeg","image6.gif", "image7.jpeg", "image1.jpeg"];
var num = 0;
if (rotator.onmouseover == )
var changeImage = function() {
var len = images.length;
rotator.src = imageDir + images[num++];
if (num == len) {
num = 0;
}
};
setInterval(changeImage, delayInSeconds * 1000);
})();
</script>
if (rotator.onmouseover == )
{
}
we must check something in if conditon.
empty condition is a problem.please check it.

Categories

Resources