change image using javascript based on function result - javascript

I've been searching and trying to figure this out for hours but i seem to be missing something. Basically i'm trying to make it so if i click a link/button it executes a script to increase or decrease the number by a specified amount in a function. (in this example its by 1)
The image files that im trying to display are supposed to change depending on the final result. but the image never changes.
any suggestions are greatly appreciated
<script type="text/javascript">
var p1hps = 20;
var p1hpimage
function p1p1Click() {
p1hps = (p1hps +1);
function p1health(){
};
}
function p1health() {
p1hpimage = "images/p1" + p1hps + ".png";
document.getElementById('p1hp').src = p1health();
}
</script>
<body>
<img src="images/p1p1.png" width="165" height="87" alt="">
<img src="images/p120.png" id="p1hp" width="324" height="252" alt="">
</body>

You need to invoke the p1health function inside p1p1Click, instead you were declaring another function with the name p1health inside p1p1Click.
Also the images src property, you need to assign the value of the variable p1hpimage instead of recursively calling the p1health method
var p1hps = 20;
function p1p1Click() {
p1hps++;
p1health();
}
function p1health() {
var p1hpimage = "images/p1" + p1hps + ".png";
document.getElementById('p1hp').src = p1hpimage ;
}
Demo: Fiddle -- inspect the source with dev tools to see the src getting updated

Try this :
var _myPicArray =new Array("pic1.png","pic2.png","pic3.png");
function p1health(n) {
document.getElementById('p1hp').src = myPicArray[n] ;
}

Related

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>

Trying to get an image to show dependent on a result of a previous function

I am very new to javascript so please be very gentle and explain things as much as you can be bothered to please ;)
I am trying to create a button that will randomly select a name from a list and display it with an image of the person (hero if you know what this is for).
I have so far the a button that runs a function that selects the name randomly, I'm just having difficulty getting the image to show...
<html>
<body>
<button onclick="myFunction()">Random</button>
<script>
function myFunction()
{
var strings = ['Axe', 'Bane', 'Batrider' ];
var randomIndex = Math.floor(Math.random() * strings.length);
var randomString = strings[randomIndex];
document.write(' ' + randomString);
}
</script>
<script type="text/javascript">
var picData = [
['Axe','http://ponky.org/~ropedy/DC/icons/heroes/Axe.png'],
['Bane','http://ponky.org/~ropedy/DC/icons/heroes/Bane.png'],
['Batrider','http://ponky.org/~ropedy/DC/icons/heroes/Batrider.png']
];
window.onload=myFunction(){
var cookieValue = 'Axe';
for(i=0; i < picData.length; i++){
if(cookieValue == picData[i][0]) {
document.getElementById('imgCont').src = picData[i][1];
i=picData.length;
}
}
}
</script>
<div>
<img id="imgCont" src="" alt="" />
</div>
Change your window.onload to something like this:
window.onload = function() {
myFunction();
// then the rest of your stuff to set the .src
}
But it looks like what you actually want to do is move the stuff for setting the .src to a separate function so you can call it in response to your button click.
Something like:
var picData = [
['Axe','http://ponky.org/~ropedy/DC/icons/heroes/Axe.png'],
['Bane','http://ponky.org/~ropedy/DC/icons/heroes/Bane.png'],
['Batrider','http://ponky.org/~ropedy/DC/icons/heroes/Batrider.png']
];
function myFunction()
{
var randomIndex = Math.floor(Math.random() * picData.length);
var randomString = picData[randomIndex][0];
document.write(' ' + randomString); // Note: I'd generally avoid document.write
document.getElementById('imgCont').src = picData[randomIndex][1];
}
Now you can call this both from onload and onclick if you want to give you a random image when first loaded and a random image each time you click the button.
For easy to read and maintain code, I'd also replace your array or arrays with an array of object literals:
var picData = [
{name:'Axe', imageUrl:'http://ponky.org/~ropedy/DC/icons/heroes/Axe.png'},
{name:'Bane', imageUrl:'http://ponky.org/~ropedy/DC/icons/heroes/Bane.png'},
{name:'Batrider', imageUrl:'http://ponky.org/~ropedy/DC/icons/heroes/Batrider.png'}
];
Why? Because now instead of:
picData[randomIndex][1];
I can write:
picData[randomIndex].imageUrl;
Which is a lot more readable and makes it clearer what you are actually doing.

Replace image with another image, then replace again after timeout - Javascript

I'm trying to do the following:
onClick, replace image1 with image2, then after 5 seconds, replace image 2 with image 1 again.
Image 1 is replaced with image 2, but my problem is that it doesn't revert back after the timeout.
Here is my code:
<img id="loadimg" style="display:none;" src="images/Loader.gif" width="140" height="30" />
<script type="text/javascript" language="javascript">
function showLoad(){
document.getElementById('Generate1').src=document.getElementById('loadimg').src;
setTimeout(showCode(), 5000);
}
function showCode(){
document.getElementById('loadimg').src=document.getElementById('Generate1').src;
}
</script>
<td colspan="3" rowspan="3"><img src="images/BUTTON.gif" alt="" name="Generate1" width="168" height="40" id="Generate1" onClick="showLoad()"></td>
Thanks for any help.
That is because old images is being "run-over" by new one. You could do something like this:
var pathToGenerateImg = "..."; // path to generate
var pathToLoadImg = "..."; // path to load img
function showLoad(){
document.getElementById('Generate1').src = pathToLoadImg;
setTimeout(showCode, 5000);
}
function showCode(){
document.getElementById('Generate1').src = pathToGenerateImg ;
}
In this case you only need single <IMG> container (with id="Generate1") as all paths are stored in variables.
You have to address the same image with id Generate1 and store initial image src in temp value (e.g. var image):
var image = document.getElementById('Generate1').src;
function showLoad(){
document.getElementById('Generate1').src = document.getElementById('loadimg').src;
setTimeout(showCode, 5000);
}
function showCode(){
document.getElementById('Generate1').src = image;
}
You don't want to run showCode and pass the result to setTimeout, you want to pass the function itself as an argument to setTimeout so it can be called back:
setTimeout(showCode, 5000);
Also, when you assign document.getElementById('loadimg').src to document.getElementById('Generate1').src, doing the reverse won't change anything. You need to keep the original in a variable. You may as well keep your elements in variables, too:
var Generate1 = document.getElementById('Generate1');
var loadimg = document.getElementById('loadimg');
var originalSrc = Generate1.src;
function showLoad() {
Generate1.src = loadimg.src;
setTimeout(showCode, 5000);
}
function showCode() {
loadimg.src = originalSrc;
}

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