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>
Related
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:
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/
I'm trying to display one image in loop. Knowing the path and image-name are okay is this example, how to display one image in loop, and when the image haven't been found, the browser displays the last right image-name until the image-name is found?
#{int j=1;}
<img src="" />
<script>
(function () {
for (var i = 1; true; i++) {
#{ string file = "/MonitoringN/../bitmaps/" + j + ".png"; bool a = System.IO.File.Exists(file) == true; }
var str = "/MonitoringN/../bitmaps/" + i + ".png";
var b = "#a";
if (b)
{
setInterval(function () { $('img').prop('src', str); }, 1000);
} else {
i--;
#{j--;}
}
#{j++;}
}
});
</script>
Because when I execute this code, I get a blank image, and then I can't see the page is loading.
Thanks a lot!
I think I know what you are trying to do ...
If I understand the question correctly, you have a list of images and you want to try to open them until one of them is found. If an image is NOT found, you want to skip to the next one.
First -- I'd simply for your question by separating the Razor stuff and the Javascript off into very separate pieces. In fact, I'm going to skip Razor entirely.
<html>
<head>
<title>A test</title>
</head>
<body>
<img src="http://x.invalid" id="myImage">
<script>
var imgs = [
"http://x1.invalid/none",
"https://www.google.com/images/srpr/logo11w.png",
"http://thedailywtf.com/Resources/Images/Primary/logo.gif"
];
var imageIndex = 0;
function tryNextImage() {
var img = document.getElementById("myImage");
img.onerror = function() {
imageIndex++;
tryNextImage();
}
img.src = imgs[imageIndex];
}
// start the ball rolling
tryNextImage();
</script>
</body>
</html>
I'm trying to create an image rotator that displays certain images at certain times, but also rotates at other times in the day.
When I first created it, I just had it rotate every three seconds. That worked fine. But once I added the code to make a different image show up at different times, it quit working all together. Part of the problem is I'm confused about where I should put the setInterval and clearInterval. Anyway, here;s the code.
<img id="mainImage" src="/arts/rotatorpics/artzone.jpg" />
JS:
var myImage = document.getElementById("mainImage");
var imageArray = ["arts/rotatorpics/artzone.jpg",
"arts/rotatorpics/bach.jpg",
"arts/rotatorpics/burns.jpg"];
var imageIndex = 0;
var changeImage = function() {
mainImage.setAttribute("src", imageArray[imageIndex]);
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
var newDay = new Date(); //create a new date object
var dayNight = newDay.getHours(); //gets the time of day in hours
function displayImages() {
if (dayNight >= 10 && dayNight <= 12) {
mainImage.setAttribute("src", imageArray[1]);
} else if (dayNight >= 17 && dayNight <= 19) {
mainImage.setAttribute("src", imageArray[2]);
} else {
var intervalHandle = setInterval(changeImage, 3000);
}
myImage.onclick = function() {
clearInterval(intervalHandle);
};
}
first of all, all your variables seem to be are global, please dont do that, use an anonymous function-wrapper which executes your code (immediately (read about IIFE here. this is not part of your problem, but just good and clean coding style.
(function() {
// your code here
})();
then i think one of your problems is your displayImages-function, which you declare but never call!
just should call it at the end of your code (or just leave it out)
displayImages();
if you want your images not to be swapped between 10-12 and 17-19 your code should then work as expected. if the images should swap even at this times, you shouldnt put the setInterval into the last else (inside your displayImages-function
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' />