Uncaught TypeError: Cannot set property 'src' of null...Choose your own adventure - javascript

I'm just learning javascript and I'm having some trouble. I'm making a choose your own adventure game where you go through a maze. There are pictures showing you what is going on. The pictures will change after each decision you make. I have a problem changing the pictures after typing in left or right. I keep getting Uncaught TypeError: Cannot set property 'src' of null error messages every time it tries to load the picture. Java says that the problem is occuring at Line 66
Here is my code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Brian.Bosco-Hazey Maze Adventure</title>
<script type="application/javascript">
var flag;
var output;
var name;
var n1 = "what is your name?"
var s1 = "You wake up in a spooky maze. You must find your way out or this place will become your grave. You can go <b>Left</b> or <b>Right</b>?";
var s2 = "You come across a wizard at a fork in the maze. He gives you a magic sword to defend yourself with. You can either go <b>Left</b> or <b>Right</b>?";
var e1 = "You encounter a monster. you attempt to escape, but it pounces on you and tears off your flesh. You have died. GAME OVER. Type restart to try again";
var e2 = "You come across a dead end, looks like you have to go back the way you came. When you turn around you step on a trap on the floor and the whole tunnel collapses on you. You did not survive. Please type restart to try again."
var e3 = "While walking down this long hallway, you come across a giant monster guarding the exit door. You take the sword the wizard gave you and you slay the beast. You go through the door and exit the maze. Congradulations you have beaten the game! Type restart to play again. ";
var done = "What are you doing? You are still dead. Type restart to start again";
var myImage;
var newImage;
function init(){
output = document.getElementById('output');
output.innerHTML="";
flag="n1";
texter(n1);
name = "";
document.body.style.background="white";
}
function texter(newText){
console.log(newText+" from texter");
var oldText = document.getElementById('output').innerHTML;
document.getElementById('output').innerHTML= newText;//+" "+oldText;
}
function Imger(newImage){
document.getElementById('img1').src = newImage;
document.getElementById('img2').src = newImage;
}
function game(){
var input = document.getElementById('input').value;
console.log("the input is "+input);
if(input=="restart"){
init();
}else{
if(flag=="n1"){
name = input;
flag="s1";
texter("hello "+name+" "+s1);
document.getElementById('img1').src = "hooded man.jpg";
output.style.color="blue";
}else if(flag=="s1"){
//ask c1
if(input=="right"){
flag="s2";
texter(s2);
document.body.style.background="green";
}else if(input=="left"){
texter(e1);
flag ="e1";
document.getElementById('img2').src = "last scene.jpg";
}else{
texter("error");
}
}else if(flag=="s2"){
//ask c2
if(input=="right"){
flag="e2";
texter(e2);
document.body.style.background="red";
}else if(input=="left"){
texter(e3);
flag ="e3";
document.body.style.background="yellow";
}else{
texter("error");
}
}else if(flag=="e1"){
//e1
texter(done);
}else if(flag=="e2"){
//e2
texter(done);
}else if(flag=="e3"){
//e3
texter(done);
}
}
}
</script>
</head>
<body onLoad="init()">
<img src="start.jpg" id="img1" width="500" height="500">
<p id="output">this is the start text</p>
<input type="text" id="input">
<input type="button" value="submit" onClick="game()" ">
</body>
</html>

document.getElementById('img2').src = newImage;
There is no id="img2" in the HTML, so document.getElementById('img2') == null.
May you can add one under img1:
<img src="start.jpg" id="img1" width="500" height="500">
<img src="start.jpg" id="img2" width="500" height="500">
OR you can remove the JS line:
document.getElementById('img2').src = newImage;
And also:
document.getElementById('img2').src = "last scene.jpg";
Or change it to:
document.getElementById('img1').src = "last scene.jpg";

I was had same problem and i just did like this and work:
function Imger(newImage){
document.getElementById('img1').src = newImage;
if(document.getElementById('img2') != NULL){
document.getElementById('img2').src = newImage;
}
}
just used if not NULL for it.
if(image != NULL){
image.src = 'image url';
}

although I won't be much help since this was asked 3 years ago by that script should actually be after the img and the img should be behind it and than it should possibly work. I would say that you have no id's of img2 but someone already pointed it out and if his suggestion doesn't work that do my suggestion.

Related

How to change source of image on click to one source and back to different source on same click

When the button is clicked the source of the image must be changed to something and when it is clicked again the source should be changed back to the previous one. Kind of like an animation of sort except that i control it with a button
the code which i have tried and failed is:
DOCTYPE html>
<html>
<body>
<img id="myImage" src="a.png" alt="a" border="0">
<button type ="button" onclick="change()">Click Me</button>
</body>
<script>
var x = document.getElementById("myImage")
function change(){
if x.src="a.png"
document.getElementById("myImage").src = "b.png"
else x.src="a.png"
}
</script>
</html>
What should i change in my code or is there a simpler code
Try this:
var x = document.getElementById("myImage")
function change(){
if (x.src == "a.png")
x.src = "b.png"
else
x.src = "a.png"
}
</script>
Can also do instead of if statement:
x.src = (x.src == "a.png" ? "b.png" : "a.png");
I think this is what you are locking at:
It took me so long to find the pictures, sorry ㅋㅋㅋ
var imgA = 'http://i.imgur.com/v5o8MW8.jpg'
var imgB = 'http://i.imgur.com/v1Vb6RR.jpg'
var x = document.getElementById("myImage")
function change() {
x.src = (x.src == imgA ? imgB : imgA);
}
<body>
<button type="button" onclick="change()">Click Me</button></br>
<img id="myImage" src="http://i.imgur.com/v5o8MW8.jpg" alt="a" border="0">
</body>
You forgot about ():
function change(){
if (x.src="a.png")
document.getElementById("myImage").src = "b.png"
else x.src="a.png"
}
MOAR: https://www.w3schools.com/js/js_if_else.asp
If you are trying to toggle the image you can just use a global variable as below:
var x = 1;
function change(){
if (x == 1)
{
document.getElementById("myImage").src = "../Images/arrow.png";
x = 0;
}
else
{
document.getElementById("myImage").src="../Images/Add.png";
x = 1;
}
}
Harikrishnan's way is one way of doing it. Another way would be by use of custom data-* attributes.
So your HTML would become:
<img id="myImage" data-change="b.png" src="a.png" alt="a" border="0">
And your Javascript would be:
function change(){
var new_src = x.getAttribute('data-change'); // get the new source
x.setAttribute("data-change", x.src); // set the custom attribute to current source
x.src = new_src; // set the image source to new source
}
UPDATE
Just realized you had syntax error and a typo in your solution.
if x.src="a.png"
document.getElementById("myImage").src = "b.png"
else x.src="a.png"
should become
if(x.src == "a.png")
x.src = "b.png"
else
x.src="a.png"
You were missing () in your if statement and also using a single = which will assign a value and not compare values.

JavaScript Display Image and Text Rather than Alert Message

I'm a newbie and starting to learn coding. I have a question regarding the famous "How many fingers am I holding up?" project. So instead of an alert message, I want the actual image of a finger with 1-5 and the message of either it is correct or not.
I think there are jquery codes.. but i don't want to jump to jquery and learn hardcore javascript first. I'm stuck with creating image Arrays and cannot manage to make the image come up.
Here's the code I have:
<body>
<p>How many fingers am I holding up?</p>
<p><input type="text" id="guess"> <button id="checkGuess">Guess!</button></p>
<div id="image"></div>
<div id="text"></div>
<script type="text/javascript">
var imgArray = new Array();
imgArray[1] = new Image();
imgArray[1].src="images/1.png";
imgArray[2] = new Image();
imgArray[2].src="images/2.png";
imgArray[3] = new Image();
imgArray[3].src="images/3.png";
imgArray[4] = new Image();
imgArray[4].src="images/4.png";
imgArray[5] = new Image();
imgArray[5].src="images/5.png";
document.getElementById("checkGuess").onclick = function() {
var randomNumber = Math.random();
randomNumber = randomNumber * 6;
randomNumber = Math.floor(randomNumber);
if (document.getElementById("guess").value == randomNumber) {
doument.getElementById("image").innerHTML = imgArray[num] + alert("Well done! You got it!");
} else {
alert("Nope! The number was " + randomNumber);
}
}
</script>
</body>
Thanks Guys! Appreciate your help!
Cheers!
Char
I think you can do something like this fiddle.
https://jsfiddle.net/6a4p2po4/5/
What I did was to make the imgArray an array of src of images, and updated the img src depending on the result.
I noticed while working you have some typos and unset variables.
For example, "doument" is misspelled, and "'num'" is not set.
doument.getElementById("image").innerHTML = imgArray[num] + alert("Well done! You got it!");
It might help to use Chrome or another browser to check the console (F12). It will definitely help you debug.
Using console.log() instead of alert() will make it show up as a log instead of a pop up window, so you can check the values that you stored on variables, i.e. console.log(randomNumber);
You're on the right track! Good job so far!
You said
So instead of an alert message, I want the actual image of a finger...
which leads me to think that we never want to call alert() and instead want to display an image and a message. Assuming I am correct in my supposition, here is some code...
<html>
<head>
<!-- some other stuff... -->
<!-- CSS is your friend! -->
<style>
.hidden {
display: none;
}
</style>
</head>
<body>
<p>How many fingers am I holding up?</p>
<p>
<input type="text" id="guess">
<button id="checkGuess" onclick="checkGuess()">Guess!</button>
</p>
<div id="image">
<!-- We can put the images in here then just hide/show them, which is much easier! -->
<img class="hidden" src="./images/1.png"/>
<img class="hidden" src="./images/2.png"/>
<img class="hidden" src="./images/3.png"/>
<img class="hidden" src="./images/4.png"/>
<img class="hidden" src="./images/5.png"/>
</div>
<div id="text"></div>
<script>
function checkGuess(){
var actualFingerCount = Math.floor(Math.random() * (5 - 1 + 1)) + 1;
//the `+` casts the value into a number
var userGuess = +document.getElementById('guess').value;
//get all of our images
var images = document.querySelectorAll('img');
//hide all of them just to be safe
images.forEach(function(img){
img.classList.add('hidden');
});
//then show the one we want
images[actualFingerCount - 1].classList.remove('hidden');
var textDiv = document.getElementById('text');
if(actualFingerCount === userGuess) {
textDiv.innerHTML = 'Yay, you got it!';
}
else {
textDiv.innerHTML = 'Whoops, try again! The number was ' + actualFingerCount + '.';
}
}
</script>
</body>
</html>
And there you have it!
Notice that this is a contrived example. In the real world, you should never define functions in the global namespace, nor should you rely on elements being in a certain order, like I did with the images. Maybe you can take it and improve it to follow better coding standards!

Javascript stops working when I change the desired output

//THIS CODE WORKS PERFECTLY, IT PLACES A RECOMMENDATION IN A DIV (Suggestion) BASED ON LIGHT STATUS
function getIntLght(){
var textIntLght = document.getElementById("selIntLght").value;
var textDSL = document.getElementById("selDSL").value;
document.getElementById("intLght").innerHTML= "Internet light Status: " + textIntLght;
//recommend if trouble shooting script based on light status of DSL and Internet
if(textDSL=="Flashing/Off"){
document.getElementById("suggestion").innerHTML= "Consider NO Sync";
} else if (textDSL =="Solid" && (textIntLght=="Red/Amber" || textIntLght=="Off")){
document.getElementById("suggestion").innerHTML= "Consider NO ROUTE";
} else {
document.getElementById("suggestion").innerHTML="Consider WALLED GARDEN OR CONNECT NO BROWSE";
}
}
// TRYING TO MAKE CORRESPONDING DIV OPEN INSTEAD OF JUST POPULATING THE SUGGESTION DIV- BROKEN, DOES NOT WORK
// "if" works, but not "if else" or "else", even though the logic is the same as above and works there.
function getIntLght(){
var textIntLght = document.getElementById("selIntLght").value;
var textDSL = document.getElementById("selDSL").value;
document.getElementById("intLght").innerHTML= "Internet light Status: " + textIntLght;
//recommend if trouble shooting script based on light status of DSL and Internet
if(textDSL=="Flashing/Off") {
document.getElementById("noSync").style.display="block";
document.getElementById("noRoute").style.display="none";
document.getElementById("CNB").style.display="none";
} else if (textDSL =="Solid" && (textIntLght=="Red/Amber" || textIntLght=="Off")){
document.getElementById("noRoute").style.display="block";
document.getElementById("noSync").style.display="none";
document.getElementById("CNB").style.display="none";
} else {
document.getElementById("CNB").style.display="block";
document.getElementById("noSync").style.display="none";
document.getElementById("noRoute").style.display="none";
}
}
Please let me know if you see what I am missing… I can’t find my error
I did correct the typo in .style.display, but it is still not working.
Thanks for pointing that out, but something is still wrong.
You have a few typos, sytle instead of style
Have you tried using === for your if/else if statements? This link explains the difference between == and ===.
<html>
<body>
<input type="text" id="selIntLght"/>
<input type="text" id="selDSL"/>
<button onclick="getIntLght()">submit</button>
<div id="intLght"></div>
<div id="suggestion"></div>
<div id="noSync" style="display:none">No sync</div>
<div id="noRoute" style="display:none">No Route</div>
<div id="CNB" style="display:none">CNB</div>
<script>
function getIntLght(){
var textIntLght = document.getElementById("selIntLght").value;
var textDSL = document.getElementById("selDSL").value;
document.getElementById("intLght").innerHTML= "Internet light Status: " + textIntLght;
//hide divs initially
document.getElementById("CNB").style.display="none";
document.getElementById("noSync").style.display="none";
document.getElementById("noRoute").style.display="none";
//recommend if trouble shooting script based on light status of DSL and Internet
if(textDSL==="Flashing/Off"){
document.getElementById("suggestion").innerHTML= "Consider NO Sync";
document.getElementById("noSync").style.display="block";
} else if (textDSL =="Solid" && (textIntLght=="Red/Amber" || textIntLght=="Off")){
document.getElementById("suggestion").innerHTML= "Consider NO ROUTE";
document.getElementById("noRoute").style.display="block";
} else {
document.getElementById("suggestion").innerHTML="Consider WALLED GARDEN OR CONNECT NO BROWSE";
document.getElementById("CNB").style.display="block";
}
}
</script>
<html>

Uncaught typeError undefined is not a function

I debugged my code plenty, but I am still having issues. This is a class assignment and I asked my professor and he is stunned as well. I am certain that fixing this error will help me with my code, but what I got wrong I am not sure. Could you help? Here is the error
Here my html code
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Magic Word - Sample</title>
<script src="magicWord.js"></script>
</head>
<body>
<div>
<h2 align="center">WELCOME TO MAGIC WORD!</h2>
<h3>Please enter your guess on the space below:</h3>
<div>
<input type="text" id="guestGuess" />
<input type="submit" id="submitButton" onclick="javascript:enteredGuess();" />
</div>
</div>
<div>
<h3>Your guesses so far are: </h3>
<div id="userGuesses"></div>
<div>You have guessed: <span id="userAttempts"></span> times</div>
</div>
</body>
</html>
Here is my Javascript
var numOfAttempts = 5;
var numOfGuesses = 0;
var magicWord = "Just";
function guessesUsed(attemptsTaken) {
var numGuessesLeft = document.getElementById("userAttempts");
numGuessesLeft.innerHTML = attemptsTaken;
}
//function guessesLeft(attemptsLeft) {
// var numGuessesUsed = document.getElementById("guessesLeft");
// numGuessesUsed.innerHTML = attemptsLeft;
//}
function listWordsUsed(wordUsed) {
var userTrials = document.getElementbyId("userGuesses").innerText;
var divisor = document.createElement("div");
divisor.innerHTML = "<div id=" + wordUsed + ">" + wordUsed + "</div>";
userTrials.appendChild(divisor);
return;
}
function enteredGuess()
{
//A user will enter a word and the word will be checked against the magic word
//var enterGuess = prompt("What is your guess?", "Enter your guess here");
var theGuess = document.getElementById("guestGuess");
var magicWordResult;
// Used lower case for both instances to compare both words
if (theGuess.value.toLowerCase() == magicWord.toLowerCase())
{
//The user guesses the correct word
magicWordResult = "Your guess was" + theGuess + "! Nice going!";
//document.writeln("Your guess was: " + guestGuess + "\nand the magic word is " + magicWord);
}
else //The user guesses wrong
{
//When user gets it wrong increase by one the numOfGuesses
numOfGuesses ++;
magicWordResult = "Your guess was" + theGuess + ". Nice try, but that's wrong, try again. \nYou have used " + numOfGuesses + " guesses.";
// Subtract the amount of guesses from the amount of attempts
var guessesLeft = numOfAttempts - numOfGuesses;
if (numOfGuesses == numOfAttempts)
{
// When the user has reached all its attemps
magicWordResult = "Sorry, you ran out of guesses. The magic word was " + magicWord + ".";
}
else
{
magicWordResult = "You still have " + guessesLeft + " guesses left.";
}
//To show the number of guesses the user has used
guessesUsed(numOfGuesses);
//To show the number of guesses the user has left
//guessesLeft(guessesLeft);
//Creates a list of the words used by the user
listWordsUsed(theGuess);
}
// Display in an alert mode and show how the user is doing
alert(magicWordResult);
}
Where is my error?
This:
var userTrials = document.getElementbyId("userGuesses").innerText;
gets the text of the "userGuesses" element as a string, but here:
userTrials.appendChild(divisor);
your code treats it as if it were a DOM node. Because there's no "appendChild" property on a String instance, it's undefined, and that explains the error — you're trying to make a function call but the function reference is undefined instead.
edit — oh also that typo in "getElementById()" is also important, as noted by crclayton in a comment. I missed that one :) The general trick to dealing with the
undefined is not a function
error is to try and find a place where your code might come up with undefined instead of a reference to a function. The primary causes, in my experience, are:
Typos, like the "getElementbyId" thing. If the function name is misspelled, JavaScript won't understand that and so it can't give a better error.
Unsatisfied assumptions about what a variable or property refers to, as in the userTrials variable.
Assumption that some function returns a reference to a function, when it in fact (might) return undefined

Why "Microsoft JScript runtime error: Object expected"?

I'm about 1 day old in using jquery, and is currently having a nightmare with it. I alreadt spent half of my day trying to get rid of this error.
I did some reading after “googling” the error (sorry, Bing!) and discovered that most of these errors result from the jquery file not being properly loaded. Okay…that started to point me in the right direction but I still couldn’t figure out why it wasn’t pathing properly. I mean, I was doing as people said – I would drag the .js file into my designer and it would print out the proper path, but still the error shows.
Here's my exact code in my editor template (with the error):
#model bool
#{
string status = "Active";
string buttonValue = "Deactivate";
string hiddenValue = "true";
if (!ViewData.Model)
{
status = "Inactive";
buttonValue = "Activate";
hiddenValue = "false";
}
}
<div style="width:100px; float:left;">
<img id = "AD_Img" src = "/Content/themes/base/images/icon_#(status).png" alt = #(status) />
<label for = "AD_Img" id = "AD_Label" >#(status)</label>
</div>
<div style="width:100px; float:left;">
<input type="button" id = "AD_Button" value = #(buttonValue) style = "width:100px" onclick = "ChangeStatus()" />
<input id = "AcntStatus" type = "hidden" name = "AcntStatus" value = #(hiddenValue) />
</div>
and in the same cshtml file, the script goes this way:
<script type="text/javascript" src="/Scripts/jquery-1.5.1.min.js">
function ChangeStatus()
{
var ButtonVal = $("#AD_Button").val();
alert(ButtonVal);
if (ButtonVal == "Deactivate")
{
var stat = "Inactive";
var buttonVal = "Activate";
var HiddenValue = "false";
}
else if (ButtonVal == "Activate")
{
stat = "Active";
buttonVal = "Deactivate";
HiddenValue = "true";
}
$("#AD_Img").attr({src: "/Content/themes/base/images/icon_"+stat+".png", alt: stat});
$("#AD_Label").html(stat);
$("#AD_Button").val(buttonVal);
$("#AcntStatus").val(HiddenValue);
}
</script>
The debugger stops on the ChangeStatus function of the input element on the following line:
<input type="button" id = "AD_Button" value = #(buttonValue) style = "width:100px" onclick = "ChangeStatus()" />
i tried to debug it by using this in my function code:
function ChangeStatus()
{
var ButtonVal = document.getElementById("AD_Button").value;
alert(ButtonVal);
}
And it works properly, it returns the exact string that I'm looking for without that error, but why? What's wrong with my codes?
Please help me figure this out.
This:
$("#AD_Img").attr(src: "../../../Content/themes/base/images/icon_"+stat+".png", alt: stat);
forces an Syntax-error. It has to be:
$("#AD_Img").attr({src: "../../../Content/themes/base/images/icon_"+stat+".png", alt: stat});
Edit:
Also take a look at your <script>, you can't mix external JS and internal JS.
This:
<script type="text/javascript" src="../../../Scripts/jquery-1.5.1.min.js">
//your code
</script>
Has to be splitted into
<script type="text/javascript" src="../../../Scripts/jquery-1.5.1.min.js"></script>
<script type="text/javascript">
//your code
</script>

Categories