Array image looping in JavaScript - javascript

I have been trying to loop traffic light images in JavaScript. I'm not sure what to do, can someone give advice.

A slight modification to your code. Here is a working sample.
I removed the dvi.count counter as it creates more confusion, We need to maintain the counters outside the function. I changed the logic to pass around the index of the image in the array starting from 0.
var image = new Array("red.jpg", "redamber.jpg", "green.jpg", "amber.jpg");
var timeout;
function stopIt() {
clearTimeout(timeout);
}
function changeimage (images, index) {
var dvi = document.getElementById(images);
if(image.length <= index)
index = 0;
dvi.src = image[index];
dvi.alt = image[index];
timeout = setTimeout('changeimage("' + images + '",' + (index + 1) + ')', 1000);
}
<body onload="changeimage('changer',0)">
<div>
<img src="t1" alt="test1" id="changer" />
</div>
</body>

I have made 3 changes to your code
Fixed the typeo div.count to dvi.count
Corrected the indenting and braces round the if statement (Not strictly necessary, but makes the code way more readable)
Replaced your nasty use of a string parameter in setTimeout to be a function reference
function changeimage(images){
var dvi=document.getElementById(images);
if(!dvi.count || dvi.count == image.length ){
dvi.count=0;
}
dvi.src=image[dvi.count];
dvi.alt=image[dvi.count];
dvi.count=dvi.count+1;
timeout=setTimeout(function(){
changeimage(images);
},3500);
}
Live example: https://jsfiddle.net/Lofug2hf/1/

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 loop to update image is returning broken image

I am new to javascript and am trying to create this loop to simulate some dice rolls. When I click roll none of the images are refreshed and it ends with the broken image shown. Can anyone see where my error is?
function roll(){
for(x=0;x<10;x++){
var die_num1 = Math.ceil(Math.random()*6);
for(y=0;y<20;y++){
var picturetype1 = Math.ceil(Math.random()*3);
if (picturetype1 == 1){prefix1 = "die-";}
if (picturetype1 == 2){prefix1 = "dicet-";}
if (picturetype1 == 3){prefix1 = "dices-";}
document.getElementById("dice").src='http://localhost/CodeIgniter_2.1.2/dice/' + prefix1 + die_num1 + '.gif';
}
}
}
body:
<input type ="button" value = "Roll" onclick="roll()" >
<img name="dice" id="dice" src="http://localhost/CodeIgniter_2.1.2/dice/die-1.gif" >
I used adocument.write to make sure that at least the final image existed in my folder and it does. I would expect to see the images cycling through as the loop progresses though. Again, I have no experience with javascript and have put this together based on how I thought it should look. Any help will be appreciated.enter code here
I wouldn't expect browser as an event-driven environment even to consider updating the screen before you return from you roll(). You need to get acquainted with setTimeout and handle it as a sequence of timer events.
Thanks for setting me in the right direction. I have reworked this to use setTimeout as Michael suggested and it is working great. Only needed 1/10 of a second per iteration, not much but made all the difference.
function roll2(){
var timer = setTimeout ("roll2();", 100);
i++;
if(i >= 15) clearTimeout(timer);
var die_num1 = Math.ceil(Math.random()*6);
var picturetype1 = Math.ceil(Math.random()*3);
if (picturetype1 == 1){prefix1 = "die-";}
if (picturetype1 == 2){prefix1 = "dicet-";}
if (picturetype1 == 3){prefix1 = "dices-";}
if (i <=15) {
document.getElementById("dice").src='http://localhost/CodeIgniter_2.1.2/dice/' + prefix1 + die_num1 + '.gif';
}
if (i >=15) {
document.getElementById("dice").src='http://localhost/CodeIgniter_2.1.2/dice/die-' + die_num1 + '.gif';
i=0;
}
}

Javascript jquery fade-in/fadeout loop, how to use timer?

New to javascript and such, trying to create a loop for fading logos using jquery.
I've got it cycling through them just fine. But i tried to make the loop continuous; so that when it reached the last logo it went back to the beginning, by resetting my for-counter to 0 every time it reached the last logo. This resulted in an infinite loop i think that crashed my browser. So i did a quick google and discovered the window.setInterval(...) timer function.
My problem is, now that firing the looping code relies on timing, i can't figure out how to calculate the interval time. For reference here's the code that fades the logos in and out (before trying to loop it):
$(document).ready(function (){
var fadeDuration = 1000;
var timeBetweenFade = 2000;
var totalTimePerChange = fadeDuration + timeBetweenFade;
var totalLogos = $('.logo').length;
var currentLogo;
var i;
for(i = 0; i < totalLogos; i++)
{
currentLogo = "#img" + i;
if(i == 0){
$(currentLogo).fadeIn(fadeDuration).delay(timeBetweenFade).fadeOut(fadeDuration);
}
else{ //general case
$(currentLogo).delay(totalTimePerChange * i).fadeIn(fadeDuration).delay(timeBetweenFade).fadeOut(fadeDuration);
}
}
});
I tried to get the time a complete loop took in a couple of ways:
$(document).ready(function (){
//..declarations..
window.setInterval( function() {
//..FOR LOOP HERE..
}, i*(fadeDuration + timeBetweenFade + fadeDuration));
});
//I also tried..
$(document).ready(function (){
//..declarations..
var timeTakenToLoop;
var startLoopTime;
window.setInterval( function() {
startLoopTime = new Date().getTime();
//...FOR LOOP HERE..
timeTakenToLoop = new Date().getTime() - startLoopTime;
}, timeTakenToLoop);
});
But in both cases I get logos starting to overlap as the function calls timing is wrong. Could someone with a bit more experience suggest what the best approach would be?
Oh and just in case anyone needs it to understand the javascript, here's the html to match..
<div id="img0" class="logo">
<img src="{% static "CSS/Images/phone_icon.gif" %}"/>
</div>
<div id="img1" class="logo">
<img src="{% static "CSS/Images/email_icon.gif" %}"/>
</div>
<div id="img2" class="logo">I can fade too</div>
Simple jQuery approach, no setTimeout and no setInterval.
var loop = function(idx, totalLogos) {
var currentLogo = "#img" + idx;
$(currentLogo)
.delay(currentLogo)
.fadeIn(fadeDuration)
.delay(currentLogo)
.fadeOut(fadeDuration, function(){
loop( (idx + 1) % totalLogos, totalLogos);
});
}
loop(0, $('.logo').length);​
See it here.

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' />

How can I reload an image on a time interval?

I have two images that need to be reloaded in x time. I tried to do it this way:
<script>
function srcreload(){
imguser=document.getElementsByName("userimage")[0];
imgme=document.getElementsByName("me")[0];
imguser.src=imguser.src;imgme.src=imgme.src;setTimeout("srcreload()",15000);};
setTimeout("srcreload()",15000);
</script>
<img src="somesrc" name="userimage">
<img src="someothersrc" name="me">
Why isn't this working and how do I fix it? I got it to work one time, but then I must have changed something because it is no longer working.
Use var.
Don't pass a string to setTimeout, but a function.
Indent properly.
If you indent nicely, you see an extraneous }, which doesn't belong there.
var url = "...";
function srcreload() {
var imguser = document.getElementsByName("userimage")[0];
var imgme = document.getElementsByName("me")[0];
var random = "?" + Math.random();
imguser.src = url + random;
imgme.src = url + random;
setTimeout(srcreload, 15000);
}
setTimeout(srcreload, 15000);
imguser.src=imguser.src;
imgme.src=imgme.src;
does these do lines makes any sense, same value is being copied?

Categories

Resources