Having Trouble Switching Images - javascript

I'm just learning some java. I am currently learning if, else statements.
In the game I am creating, the user picks a number between 0 and 10 and puts it into an input box. If correct, the image on screen changes to one picture, if incorrect, it switches to a different picture. However, I cannot seem to get the images to change at all. I've tried a few different ways of coding; I'm currently using an img array. However, when I do the code I receive an ObjectHTMLImageElement error.
Here is my current code:
<div id="top">
<h1>Pie in the Face</h1>
<p>Guess how many fingers I'm holding up between 0 and 10.
<br /> If you guess correctly, I get a pie in the face.
<br /> If you guess wrong, you get a pie in the face.</p>
<input id="answer" />
<button id="myButton">Submit</button>
</center>
</div>
<div id="container">
<div id="image"></div>
<div id="manpie"></div>
<div id="girlpie"></div>
</div>
<script type="text/javascript">
var x = Math.random();
x = 11 * x;
x = Math.floor(x);
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = "images/manpie2.jpg";
imgArray[1] = new Image();
imgArray[1].src = "images/girlpie2.jpg";
document.getElementById("myButton").onclick = function() {
if (x == document.getElementById("answer").value) {
document.getElementById("image").innerHTML = imgArray[0];
// what I had document.getElementById("image").innerHTML=imgArray[0];
} else {
document.getElementById("image").innerHTML = imgArray[1];
}
}
</script>
</body>
I have also tried using lines such as: document.getElementById("image").innerHTML=document.getElementById("manpie");
and then nothing works. Here is a link to the "live" site it's on.
http://176.32.230.6/mejorarcr.com/
any help would be appreciated. Thank You!

You have to change the innerHTML value in your code:
if (x==document.getElementById("answer").value) {
document.getElementById("image").innerHTML='<img src="'+imgArray[0].src+'" />';
// what I had document.getElementById("image").innerHTML=imgArray[0].src;
} else {
document.getElementById("image").innerHTML='<img src="'+imgArray[1].src+'" />';
}
DEMO or this

change:
document.getElementById("image").innerHTML=imgArray[0];
to:
document.getElementById("image").setAttribute("src", imgArray[0]);
make sure imgArray[0] is the actual image path:
imgArray[0]="images/manpie2.jpg";
imgArray[1]="images/girlpie2.jpg";

Related

Getting Array positions in HTML automatically

I have many arrays some upto 60 some upto 100. I am trying to get the text at the 0 position of this arrays for all arrays. I am sorry I don't know how to frame the question correctly. I don't want to type (greeting[0])[1] etc for say 100 times for every greeting. This is my code so far. Can someone help me in this! The greeting[0] etc actually go till 60 etc. Is it possible to do something like let i = 0 , for greeting.length , if i < greeting.length , i++ , and somehow put (greeting[i][0]}. And the result will be such that it show the values of all greeting shows in the paragraph element or in a separate window or something. I am still new to HTML so forgive me is if this seems basic.
Edited Question Update.
P.S. Some of my Arrays have the format greeting[0] = new Greet["Hola", "Salve", "Olá"] . I had to do it such because I use the three options. Is there any way I can automate the process with this?
Edited Question - Update 1
So I have updated the code to be more representative of what I am trying to ask. Basically here I want to provide a button so that on clicking the button I can see all the English words I can choose from. So I want to do something like get the value of the English words in greeting 0, 1 etc and display them separately so that we can select which English word we want instead of just numbers which we don't know what word they represent. Can someone help me with this please!
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="English"> Select English Word </p>
<p id="French"> Click below button </p>
<p id="Italian"> Click below button </p>
<button onclick="Another()"> CLick </button>
<script type="text/javascript" src="./script.js"></script>
</body>
</html>
var greeting = [];
greeting[0] = new Word("Hi", "salut", "Ciao") ;
greeting[1] = new Word("Hello", "Salve", "Ciao") ;
greeting[2] = new Word("Welcome", "Bienvenue", "benvenuta") ;
greeting[3] = new Word("Good Day", "Bonne journée", "Buona giornata") ;
greeting[4] = new Word("Good Day", "Bonjour", "Buongiorno") ;
function Word(English,French,Italian) {
this.English = English ;
this.French = French ;
this.Italian = Italian ;
} ;
function Another() {
var nums = window.prompt("Select a number within " + greeting.length ) ;
var optionuser = greeting[nums] ;
var selection = alert("You selected English word " + optionuser.English )
document.getElementById("English").innerHTML = optionuser.English ;
document.getElementById("French").innerHTML = optionuser.French ;
document.getElementById("Italian").innerHTML = optionuser.Italian ;
}
I recommend using Array.map(callback) (see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)
document.getElementById('something').innerHTML = greeting.map(item=>item[0]).join("<br>");
I have given a slightly modified code below.Hope this is what you are looking for. Since you are new, one advise is not to use window.prompt in your code. Explore some other way. Also change the function Word to Class Word. I think you were trying to create a Class but have given wrong keyword. Instead of prompt, I have used radio button.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Select Language:</p>
<input type="radio" id="English" name="language" value="English">
<label for="English">English</label><br>
<input type="radio" id="French" name="language" value="French">
<label for="French">French</label><br>
<input type="radio" id="Italian" name="language" value="Italian">
<label for="Italian">Italian</label><br>
<input type="radio" id="Spanish" name="language" value="Spanish">
<label for="Spanish">Spanish</label><br>
<button onclick="Another()">Click</button>
<p id="msg"></p>
<script>
class Word {
constructor(English,French,Italian){
this.English = English ;
this.French = French ;
this.Italian = Italian ;
}
} ;
var greeting = [];
greeting[0] = new Word("Hi", "salut", "Ciao") ;
greeting[1] = new Word("Hello", "Salve", "Ciao") ;
greeting[2] = new Word("Welcome", "Bienvenue", "benvenuta") ;
greeting[3] = new Word("Good Day", "Bonne journée", "Buona giornata") ;
function Another() {
let optionSelected = document.querySelector('input[name="language"]:checked').value;
document.getElementById('msg').innerHTML += 'You selected:'+optionSelected;
for(let i=0;i<greeting.length;i++){
document.getElementById('msg').innerHTML += '<br>' + greeting[i][optionSelected];
}
}
</script>
</body>
</html>
Note: Use separate .js file as you did. For answering purpose i have used inline style.

How to insert an ID from an HTML document into a VAR function in JavaScript?

Im trying to make an 'online' (HTML document) file that has an input to solve math, and I need a way to type in the numbers, and insert a 'solve me' button. I have the button, and the form by ID and class as well.
This is what I inserted into a "try it" prompt box through w3schools.com site, tried looking almost everywhere within that site to try to input it in.
<div id="A"></div>
<div id="B"></div>
<script>
var A = 1;
var ele = document.getElementById('A');
var y = 2;
var z = A + y;
document.getElementById("demo").innerHTML = z;
</script>
Is there a way to do this? And thank you guys for your help!
<!DOCTYPE html>
<html>
<body>
<input id="A"/>
<input id="B"/>
<div id="demo"></div>
<button onclick="add();">ADD</button>
<script>
function add () {
var A = document.getElementById('A').value *1;
var B = document.getElementById('B').value *1;
var z = A + B;
document.getElementById("demo").innerHTML = z;
}
</script>
</body>
</html>
Hope this helps you, here you need to use input to have a user editable field,a div as you guessed to display your answer and button which triggers some logic.

Evaluating a URL with JavaScript

I wrote a webpage that displays a slideshow of different images that users can look through. However, I need to write a function so if they click on a URL that says
http://www.slideshow.com/image3
The slideshow will automatically show "Image 3" in the slideshow when the page is loaded. I have researched this for days, trying to use AJAX, ASP, and various jQuery and .js files, but nothing I have researched seems to fit my purpose. Is there a simpler way to do this with just JavaScript?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Slideshow</title>
<script type="text/javascript">
//preloading all the images into a cache
//to add more slides, add extra variable declarations
var img1 = new Image()
img1.src = "img/1.jpg"
var img2 = new Image()
img2.src = "img/2.jpg"
var img3 = new Image()
img3.src = "img/3.jpg"
var img4 = new Image()
img4.src = "img/4.jpg"
var img5 = new Image()
img5.src = "img/5.jpg"
var img6 = new Image()
img6.src = "img/6.jpg"
var img7 = new Image()
img7.src = "img/7.jpg"
var img8 = new Image()
img8.src = "img/8.jpg"
var img9 = new Image()
img9.src = "img/9.jpg"
var imgNum = 1
var x = 0
var width
//function that cycles through different images
function slideshow()
{
if (!document.images)
return
if (imgNum < 9) // <-- If you add or subtract images in the slideshow, you need to change this number to the amount of
imgNum++ //images in the slideshow so it will loop correctly.
else
imgNum=1
document.images.slide.src=eval("img" + imgNum + ".src")
}
//function that crops the slideshow image to the screen size and centers it
function crop()
{
if (document.getElementById("slide").width > screen.width)
{
width = document.getElementById("slide").width
width = -1*((width - screen.width)/2)
document.getElementById("slide").style.marginLeft= width +"px"
document.getElementById("slide").style.marginRight= width + "px"
}
}
//function that evaluates a number passed to it and returns the corresponding image in /img
function imgSelect(x)
{
imgNum = x
document.images.slide.src=eval("img" + imgNum + ".src")
}
//function that hides or shows the menu
function hide(object)
{
if (object.style.display=="none")
object.style.display="block"
else
object.style.display="none"
}
//function that changes the menu text from "hide menu" to "show menu" and vice versa
function menuChange(object)
{
if (object.innerHTML=="hide menu")
object.innerHTML="show menu"
else
object.innerHTML="hide menu"
}
//function that allows a link to do both the hide(object) function and the menuChange(object) function with once click
function doBoth(object1, object2)
{
hide(object1)
menuChange(object2)
}
</script>
</head>
<body onload="crop()">
<center>
<div style="background-color:#87D300; padding:5px;">
<a id="button" href="javascript:doBoth(document.getElementById('menu'),document.getElementById('button'))" style="color:#FFFFFF">hide menu</a>
</div>
</center>
<img src="img/logo.png"/>
<div id="title">
<h1 style="position:relative; top:-31px; right:-133px">Slideshow</h1>
</div>
<div id="menu" class="margin">
<h2>Designs</h2>
<ul>
<li>Splash Page:1</li>
<li>Splash Page:2</li>
<li>Splash Page:3</li>
<li>Splash Page:4</li>
<li class="new">Book: 1</li>
<li>Book: 2</li>
<li>Book: Rollover</li>
<li>Book: Clicked</li>
<li>Book: Clicked, no Email</li>
</ul>
</div>
</br>
<center>
<div id="mySlides" style="width:screen.width; overflow:hidden;">
<img src="img/1.jpg" onclick="slideshow()" id="slide"/>
</div>
</center>
</body>
</html>
Use a URL hash instead:
http://www.slideshow.com#image3
The value will be document.location.hash, which you can use for read/write. Any other manipulation of the URL will cause a navigation event.

javascript dice game - image does not change

Having a slight issue calling a math.random image for a dice game. When I click the roll button the image does not change. I have the images saved where the .html file is. Any help is much appreciated!
Roll The Dice
<script type="text/javascript">
var dieImage;
function start()
{
var button = document.getElementById(rollButton);
button.addEventListener("click", rollDice, false);
dieImage = document.getElementById("die1");
}
function rollDice()
{
setImage(dieImage);
}
function setImage(dieImg)
{
var dieValue = Math.floor(1 + Math.random() * 6);
dieImg.setAttribute("src", "die" + dieValue + ".jpg");
dieImg.setAttribute("alt", "dieImg with" + dieValue + "spots");
if (dieValue == 6)
{
document.getElementById("sometext").innerHTML = "You Win!";
}
else
{
document.getElementById("sometext").innerHTML = "Roll Again";
}
}
window.addEventListener("load", start, false);
</script>
</head>
<body>
<form action = "#">
<input id = "rollButton" type = "button" value = "Roll Dice">
</form>
<li>
<img id = "die1" src = "die1.jpg" alt = "blankImage">
</li>
<div id = "sometext">Roll for a 6!</div>
</body>
The only issue with the code above is this line:
var button = document.getElementById(rollButton);
Should read
var button = document.getElementById("rollButton");
The above change DOES cause the function to work, and the image to be updated. Assuming all of your images are in fact in the right place, you will see them change.
As a note of encouragement, I would suggest you code in Firefox, and get Firebug. With these tools, you can then utilize the Firebug console and/or Firefox's Web Developer Error Console. These are tremendously useful for troubleshooting problems like this quickly.

Drop down menu showing improper images based on selection

I have a drop down box that will change an image if a new selection is made. Which i have got to work using the following code
<HTML>
<HEAD>
<TITLE>JS1</TITLE>
<script LANGUAGE="JAVASCRIPT TYPE="TEXT/JAVASCRIPT">
<!--
image1 = new image(120,90)
image1.src = "desk1.gif"
image2 = new image(120,90)
image2.src = "desk2.gif"
image3 = new image(120,90)
image3.src = "desk3.gif"
image4 = new image(120,90)
image4.src = "desk4.gif"
function loadCatch(list)
{
var img = list.options[list.selectedIndex].value
document.thumbnail.src = eval(img + ".src")
}
</SCRIPT>
</HEAD>
<BODY>
<IMG SRC="desk1.gif" NAME="thumbnail" HEIGHT="90" WIDTH="120">
<FORM>
<SELECT NAME="catch" onChange="loadCatch(this)">
<OPTION VALUE="Image1">Bands
<OPTION VALUE="Image2">Clips
<OPTION VALUE="Image3">Lamp
<OPTION VALUE="Image4">Else
</SELECT>
</FORM>
</BODY>
</HTML>
The trouble is my form has 3-4 parts so when you click back to edit the form stays selected with the correct option selected but but the image shows the default image, I know this is because it is using an onChange event so I have investigated another way using the following code:
<script language="JavaScript" type="text/javascript">
<!--
var dropdownIndex = document.getElementById('colorsselect').selectedIndex;
var dropdownValue = document.getElementById('colorsselect')[dropdownIndex].value;
document.write(dropdownValue);
//-->
</script>
Which displays the correct image if I click to go back but it isn't live (onChange) so the user doenst get immediate result showing the new image.
I'm not sure how to combine the two pieces of code above, hope someone can help?
Call that same loadCatch function onload:
1) Add an id to the select box so you can reference it elsewhere:
<select id="catch" name="catch" onchange="loadCatch(this)">
2) Call loadCatch from on body load:
<body onload="loadCatch(document.getElementById('catch'))">
3) Adjust loadCatch to do nothing if a value hasn't been selected yet:
function loadCatch(list)
{
if (list.selectedValue != -1) {
var img = list.options[list.selectedIndex].value
document.thumbnail.src = eval(img + ".src")
}
}

Categories

Resources