Image changing loop not working - javascript

I have written a JavaScript that is supposed to change my header image every three seconds. For some reason nothing happens when I'm opening my page.
Can anyone see what I'm doing wrong?
HTML:
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<script src="changeImage.js"></script>
<title>Mikael Mattsson</title>
</head>
<body>
<div class="header">
<img id="headerImg" src="images/header-image.png" alt="Header image" width="100%" hight="100%">
</div>
</body>
</html>
JavaScript:
var images = [];
images[0] = "images/header-image.png";
images[1] = "images/header-image2.png";
var x = 0;
function imageChanger(){
var img = document.getElementById("headerImg");
img.src = images[x];
x++;
if (x > images.length){
x = 0;
}
setTimeout("imageChanger()", 3000);
}

x > images.length should be x >= images.length.
setTimeout("imageChanger()", 3000); must be changed to setTimeout(imageChanger, 3000);

You call the setTimeout inside the function but never call the function. So the timeout is never set, hence the function is not called through the timeout.
I recommend using setInterval above setTimeout in your case since you want to have the function executed repeatedly. Also you could improve the way you increase x.
var x = 0;
function imageChanger() {
var img = document.getElementById("headerImg");
x = (x + 1) % images.length; // Make sure x is never larger than images.length
img.src = images[x];
}
// Start calling the function after a delay of 3000ms
setInterval(imageChanger, 3000);​​​​
I also recommend using a better name than x for your counter variable, but that is up to you!

You're close. You need to change two things.
First, you need to call the imageChanger function at least once to kick off the code. At the end of your script, add:
imageChanger();
Your code may work from there. However, instead of passing a string to setTimeout(), you should instead pass a reference to the function itself:
setTimeout(imageChanger, 3000);
You should be all set. Let me know if you have issues.

Remove
setTimeout("imageChanger()", 3000);
And add
window.onload=function() {
setInterval(imageChanger, 3000);
}
Outside the function
And as pointed out, change > to >=

Related

Problems Cycling through Images with JavaScript

I am currently having a problem with my function not correctly cycling through images. The first image I have in the html code will show, but the code attempts to switch to a second image but instead just shows the blank white background. All images lie in the same directory folder. I have checked and made sure all file names and extensions match the their true names, attempted to find any syntax errors that might be causing this not to run but to no avail. could it be the fact that I am attempting to create an array and populate it at the same time, but doing so incorrectly?
Here is the answer I based my code off of: Link
Here's my current relevant code:
JS:
<script type="text/javascript">
function displayNextImage() {
var i = (i === imgArray.length - 1) ? 0 : i + 1;
document.getElementById("image").src = imageArr[i];
}
function displayPreviousImage() {
var i = (i <= 0) ? imgArray.length - 1 : i - 1;
document.getElementById("image").src = imageArr[i];
}
function startTimer() {
setInterval(displayNextImage, 2000);
}
var imageArr = ["~/Images/Carrying Food In.jpg", "~/Images/Food Pantry.jpg", "~/Images/Fresh Produce.jpg", "~/Images/Handing Out Food.jpg", "~/Images/Man Pushing Wheelbarrow.jpg", "~/Images/Woman Leading Class.jpg"], i = -1
</script>
Relevant HTML:
<body onload="startTimer()">
<img id="image" src="~/Images/Food Pantry.jpg" style="width: auto;" />
<p></p>
</body>
Edit: Changed one method to previous (had two of the same method names) - problem still persists
That's because of misspelled reference to your array and because on every function run you redeclare iterator variable var i. This code should work:
<script type="text/javascript">
var imageArr = ["~/Images/Carrying Food In.jpg", "~/Images/Food Pantry.jpg", "~/Images/Fresh Produce.jpg", "~/Images/Handing Out Food.jpg", "~/Images/Man Pushing Wheelbarrow.jpg", "~/Images/Woman Leading Class.jpg"], i = -1
var i;
function displayNextImage() {
i = (i <= 0) ? imageArr.length - 1 : i - 1;
document.getElementById("image").src = imageArr[i];
}
function startTimer() {
setInterval(displayNextImage, 2000);
}
</script>

Javascript image swap sequence

As a task i am going to make traffic lights change in sequence when a button is pushed.I am going to do this by using a variable and adding one to it each time a image is shown therefore the computer knows what image to display next through the use of if and elses however i am not great at javascript and it will not run i have tried in many different environments for example in dreamweaver and notepad ++ but am getting no where here is what i have got :
<HTML>
<head>
<title>Untitled Document</title>
</head>
<body>
<img id="IMAGE" width="100" height="200"></img>
<button onClick="imageswap(a)">GO</button>
</body>
<script>
var a = 0
function imageswap(a)
{
if (var a==0) {
document.getElementById('IMAGE').src='red_empty_empty.png';
var a + 1;
}
else if (a==1)
{
document.getElementById('IMAGE').src='empty_amber_empty.png';
var a + 1;
}
else
{
document.getElementById('IMAGE').src='empty_empty_red.png';
var a==0;
}
}
</script>
</html>
Thank you for reading and i would appreciate anyones help.
edit:
I have taken on feedback and amended my code but when testing it does not show the image i would like instead the little x .
<HTML>
<head>
<title>JAVASCRIPT</title>
</head>
<body>
<img id="IMAGE" width="100" height="200"></img>
<button onClick="imageswap()">GO</button>
</body>
<script>
var a = 0
function imageswap()
{
if (a=0) {
document.getElementById('IMAGE').src='red_empty_empty.gif';
a = a + 1;
}
else if (a==1)
{
document.getElementById('IMAGE').src='empty_amber_empty.gif';
a = a + 1;
}
else
{
document.getElementById('IMAGE').src='empty_empty_red.gif';
var a=0;
}
}
</script>
</html>
edit:
I have taken into account some recommendations and now when i click the button the first image is shown followed by the second on a second button press however it fails to display the third image and the first and second image dont always work first time.
<HTML>
<head>
<title>JAVASCRIPT</title>
</head>
<body>
<img id="IMAGE" width="100" height="200"></img>
<button onClick="imageswap()">GO</button>
</body>
<script>
var a = 0;
function imageswap() {
if (a == 0) {
document.getElementById('IMAGE').src = 'red_empty_empty.gif';
a += 1;
} else if (a == 1) {
document.getElementById('IMAGE').src = 'empty_amber_empty.gif';
a += 1;
} else {
document.getElementById('IMAGE').src = 'red_empty_empty.gif';
a = 0;
}
}
</script>
in you first line var a = 0 you declare your counter (the var a part) and initialise it by assigning the value 0 (the a = 0 part), therefore there's no need to declare the variable again later, you just want to update it by assigning new values
so the statement if (var a==0) would be incorrect syntactically, because you can't check if a variable declaration is 0. you can of course check if the previously declared variable has a value of 0, which would be if (a==0)
same goes when you try to increment the counter value. var a + 1; is wrong, because you can't increment by 1 a declaration. you should instead assign to the existing counter, the value of itself plus 1, so a = a + 1;
finally, when you try to reset the counter, var a==0;, (beside the usual declaration error) remember that == is comparison and = is assignment. You shouldn't check if the counter is 0, you should assign the value 0 to the counter to reset it.
hope it helps
I Apply with in console.log(a).It will show the increment of a\
Apply the var a in globel It will increment on each time of you click
And increment Apply with a +=1 instead of a+1
var a = 0
console.log(a)
function imageswap(){
if (a==0) {
document.getElementById('IMAGE').src='red_empty_empty.png';
a += 1;
console.log(a)
} else if (a==1){
document.getElementById('IMAGE').src='empty_amber_empty.png';
a += 1;
console.log(a)
} else {
document.getElementById('IMAGE').src='empty_empty_red.png';
a =0;
console.log(a)
}
}
<button onclick="imageswap()">GO</button><br>
<img id="IMAGE" width="100" height="200"></img>
Ok Few things you need to take care:
You are passing a within the function imageswap(a) and you are accessing a from the value passed within the function that'll be 0 all the time. Check https://jsfiddle.net/aegwj88g/
You are checking var a==0, var a==1 which is incorrect. It should be like if(a==0) or else if(a==1).
You are trying to assig value to a with var a + 1 which is also incorrect. Left hand side must be a valid variable other than the javascript tokens (check JS naming convention) which stores the value. it should be a=a+1 (or a+=1) just as you do in maths;
Check this fiddle:

Javascript Pic Slideshow Failing?

FOr some reason my code is not executing properly. i am trying to program a slideshow with javascript. Im using a for loop to pull and populate the src files from a created array and change the pic every 3 seconds. THe page loads and the first pic is present but when the interval occurs the first pic dissapears and nothing falls in its place. What am I doing wrong?
<img name="mainSlide" id="mainSlide" src="images/mainPagePhotos/facebook-20131027-180258.png" alt="">
var mainSlidePics = ("facebook-20131027-180258.png","IMG_9694116683469.jpg","IMG_28452769990897.jpg");
window.onload = setInterval("mainSlide();", 3000);
function mainSlide() {
for(i=0; i<mainSlidePics.length; i++ ) {
document.images.mainSlide.src = "images/mainPagePhotos/" + mainSlidePics[i];
}
}
Have you tried getting the Id first?
var mainSlide = document.getElementById("mainSlide");
mainSlide.src = "images/mainPagePhotos/" + mainSlidePics[i];
also a forloop is a loop that finishes its loops even in one call.
try
var i = 0;
window.onload = setInterval("mainSlide(i);", 3000);
mainSlide(int j){
mainSlide.src = "images/mainPagePhotos/" + mainSlidePics[i];
setInterval("mainSlide(j++);", 3000);
}
First you have to correctly declare the array.
Then you have to move the counter variable outside the function triggered by setInterval.
Then pass the reference of the function to setInterval.
<img name="mainSlide" id="mainSlide" src="images/mainPagePhotos/facebook-20131027-180258.png" alt="">
<script type="text/javascript">
var mainSlidePics = ["facebook-20131027-180258.png","IMG_9694116683469.jpg","IMG_28452769990897.jpg"];
var position = 0;
function changePic() {
position = (position+1) % mainSlidePics.length;
document.images.mainSlide.src = "images/mainPagePhotos/" + mainSlidePics[position];
}
window.onload = function() {
setInterval(changePic, 3000);
};
</script>

Getting images to change in a for loop in javascript

So far I created an array with 11 images, initialized the counter, created a function, created a for loop but here is where I get lost. I looked at examples and tutorial on the internet and I can see the code is seeming simple but I'm not getting something basic here. I don't actually understand how to call the index for the images. Any suggestions. Here is the code.
<script type="text/javascript">
var hammer=new Array("jackhammer0.gif",
"jackhammer1.gif",
"jackhammer2.gif",
"jackhammer3.gif",
"jackhammer4.gif",
"jackhammer5.gif",
"jackhammer6.gif",
"jackhammer7.gif",
"jackhammer8.gif",
"jackhammer9.gif",
"jackhammer10.gif")
var curHammer=0;
var numImg = 11;
function getHammer() {
for (i = 0; i < hammer.length; i++)
{
if (curHammer < hammer.length - 1) {
curHammer = curHammer +1;
hammer[i] = new Image();
hammer[i].src="poses/jackhammer" +(i+1) + ".gif";
var nextHammer = curHammer + 1;
nextHammer=0;
{
}
}
}
}
setTimeout("getHammer()", 5000);
</script>
</head>
<body onload = "getHammer()";>
<img id="jack" name="jack" src = "poses/jackhammer0.gif" width= "100" height ="113" alt = "Man and Jackhammer" /><br/>
<button id="jack" name="jack" onclick="getHammer()">Press button</button>
Following on what Paul, said, here's an example of what should work:
var hammer=["jackhammer0.gif","jackhammer1.gif","jackhammer2.gif","jackhammer3.gif",
"jackhammer4.gif","jackhammer5.gif","jackhammer6.gif","jackhammer7.gif",
"jackhammer8.gif","jackhammer9.gif","jackhammer10.gif"];
var curHammer=0;
function getHammer() {
if (curHammer < hammer.length) {
document.getElementById("jack").src= "poses/" + hammer[curHammer];
curHammer = curHammer + 1;
}
}
setTimeout("getHammer()", 5000);
The big missing element is that you need to call getElementById("jack") to get a reference to the DOM Image so that you can change it's source. If you're using jQuery or most other JS frameworks, just type $("#jack") to accomplish the same.
I don't understand the need for the for loop at all, just increment the index value [curHammer] each time you click, and reset if it passes your max index length (in this case 11).
Pseudo-Code:
currentHammer = -1
hammers = [ "a1.jpg", "a2.jpg", "a3.jpg"]
getHammer()
{
currentHammer = currentHammer + 1;
if(currentHammer > 2)
currentHammer = 0;
image.src = hammers[currentHammer];
}
a) are you just trying to show an animated gif? If so, why not use Adobe's Fireworks and merge all those gifs into a single gif?
b) you know that the way you have it the display is going to go crazy overwriting the gif in a circle right?
c) you might want to put a delay (or not). If so, make the load new gif a separate function and set a timeout to it (or an interval).
Also, you are being redundant. How about just changing the src for the image being displayed?:
var jackHammer = new Array();
for (var i=0;i<11;i++) { //pre-loading the images
jackHammer[i] = new image();
jackHammer[i].src = '/poses/jackHammer'+i.toString()+'.gif';
} //remember that "poses" without the "/" will only work if that folder is under the current called page.
for (var i=0;i<11;i++) { //updating the image on
document.getElementById('jhPoses').src = jackHammer[i].src;
}
on the document itself,
< img id='jhPoses' src='1-pixel-transparent.gif' width='x' height='y' alt='poses' border='0' />

Simple Javascript Gallery

So I'm trying to loop through this array and change an image source every few seconds. Right now I have an onload event calling a setTimeOut method which should change the image 5 seconds after the page has loaded I would think, but it is doing it instantly. What is the problem? Here is my code:
<html>
<head>
<title>Ad Rotaror</title>
<script type="text/javascript">
var i = 0;
var ads = new Array(4);
ads[0]='promo1.gif';
ads[1]='promo2.gif';
ads[2]='promo3.gif';
ads[3]='promo4.gif';
ads[4]='promo5.gif';
function change()
{
if(i > 4)
i = 0;
document.images[0].src = ads[i];
i++;
}
</script>
</head>
<body>
<img src="promo1.gif" onload="setInterval(change(), 5000)" />
</body>
</html>
Change 'change()' to 'change'. You are calling the function immediately.

Categories

Resources