I'm super stuck. I'm creating a hangman game for a class and I cannot get the words to generate and show in my HTML. We're required to have them show as underscores but I cannot get them to show in the HTML either. I've been able to get it to show in the console but not in my HTML.Any help would be appreciated or any assistance in troubleshooting.
please see the code.
//horror movie titles selected to guess
var movieTitles = [
"halloween",
"suspiria",
"audition",
"hereditary",
"the beyond",
"the evil dead",
"the blair witch project"
];
//letters already guessed
var guessedLetters = [];
var numOfLetters = [];
//randomly assigned variable
var movieToGuess = null;
//attempts left
var livesLeft = 8;
//games won
var wins = 0;
//games lost
var losses = 0;
window.onload = function() {
updateMovieToGuess();
};
var updateMovieToGuess = function() {
for (var i = 0; i < numOfLetters.length; i++){
numOfLetters[i] = "_".join(" ");
}
var movieToGuess = movieTitles[Math.floor(Math.random() * movieTitles.length)];
document.getElementById("movie-title").innerHTML = movieToGuess;
};
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hangman</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="javascript/games.js"></script>
<link href="https://fonts.googleapis.com/css?family=IM+Fell+Double+Pica+SC" rel="stylesheet"> </head>
<body>
<p>Press any key to get started<span id='any-key'> </span> </p>
<p>Movie Title:<span id="movie-title"> </span> </p>
<p>Letters Guessed: <span id='letters'> </span> </p>
<p>Lives Remaining:<span id='lives-left'> </span> </p>
<p>Movies You've Survived:<span id='wins'> </span> </p>
<p>Movies You Died In:<span id='lost'> </span> </p>
<footer> </footer>
</body>
</html>
Two problems:
querySelector is looking for <movie-title> instead of <span id="movie-title">. To fix it, either use getElementById instead of querySelector, or change movie-title to #movie-title.
As Mark Meyer pointed out in a comment, you're using movieToGuess before you set it.
EDIT: I see you edited your question and its code after I answered it. You fixed problem #2 but not #1. Worse, you introduced a new problem: you now add the call to updateMovieToGuess via window.onload inside of updateMovieToGuess instead of at top level, so it never gets called (essentially, you've created a chicken-and-egg problem).
Related
I am currently learning about objects within class. I created an object with constructor notation in Javascript, and instantiated four different objects with distinct names. For some reason, when I try to run the Captain.speak() method in my code, it doesn't work. It should display the Captain.strPhase string that I created right before initiating the command for the function. When I check this in online compilers, there are no errors, but it doesn't output my string. Would anyone happen to know why?
$(document).ready(function() {
function Pirate(rank, phrase, id) {
output = "";
randNum = 1;
secretNum = 1;
this.strRank = rank;
this.intNum = favnum;
this.strPhrase = phrase;
this.elOutput = document.getElementById(id);
this.speak = function() {
this.elOutput.innerHTML += "<br>" + this.strPhrase;
}; //End speak
this.chooseRandNum = function() {
this.randNum = Math.floor(Math.random() * 10);
}; //End chooseRandNum
}; //End Pirate
var Captain = new Pirate("Captain", "", "captain");
var firstMate = new Pirate("First Mate", "I love guessing games!", "pirate1");
var Quartermaster = new Pirate("Quartermaster", "This game should be fun.", "pirate2");
var Gunner = new Pirate("Gunner", "Let's start playing!", "pirate3");
Captain.strPhrase = "Argh maties, ready to play a guessing game?";
Captain.speak();
}); // end of $(document).ready()
<html lang="en">
<head>
<meta charset="utf-8">
<!-- Begin every html page with everything up to this point (just use your own header block) -->
<!-- Also, feel free to remove all the instructional comments as you modify this file to make it yours. -->
<!-- This <title> displays in the page tab -->
<title>Randomness</title>
<!-- This will link to your CSS stylesheet for formatting as soon as you create the file. The page will work without it, though. -->
<link rel="stylesheet" href="css/myFancyStylesheet.css">
<!-- This links to the jQuery library so your js code will work
Always include this *before* your own js code (extremely important) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- This links to the js code specific for this page -->
<script src="Randomness.js"></script>
</head>
<body>
Captain's Guessing Game:
<br></br>
<div id="captain">
</div>
<br></br>
<div id="pirate1">
</div>
<br></br>
<div id="pirate2">
</div>
<br></br>
<div id="pirate3">
</div>
</body>
</html>
When I run your code, I get an error message:
Uncaught ReferenceError: favnum is not defined
If you comment out this line...
// this.intNum = favnum;
...everything should work just fine.
My message does not display after I run the code. Need some direction, I double checked my code. Might be a syntactical error somewhere
HTML-
<!doctype html>
<html>
<head>
<title>Message Generator</title>
<link rel="stylesheet" href="index.css">
<center><div class="wordart blues"><span class="text">Message Generator</span></div></center>
</head>
<body>
<div class="quoteDisplay"><center>Your random message will be displayed here</center></div>
<div id="quote">
<!--Quote will display here-->
</div>
<center><button onclick="messageGenerator()">Click Here</button></center>
<script src="index.js"></script>
</body>
</html>
Javascript-
const first = ["Mom", "Dad", "Uncle", "Dog", "Cat", "Brother", "Sister", "Aunt", "Random Stranger", "Respect", "Honor", "Dignity", "Brain", "Life"]
const second = ["Ocean", "Sea", "Volcano", "Tornado", "Ditch", "Cave", "Typhoon", "Asia", "India"]
const third=["Unknown","To explore","To prove a point","To live life with no constraints","Just cause"]
function randomGenerate(value) {
var item = value[Math.floor(Math.random() * value.length)];
return item;
}
const messageGenerator = () => {
let person = randomGenerate(first);
let place = randomGenerate(second);
let reason = randomGenerate(third);
let finalSentence = `Your ${person} jumped in the ${place}\nReason: ${reason}`;
document.getElementById("quoteDisplay").innerHTML=finalSentence;
}
document.getElementById("quoteDisplay") looks for an element with ID of "quoteDisplay". In this case, your targeted element is a class.
document.querySelector('.quoteDisplay').innerHTML = finalSentence
Although, I think you are trying to target #quote, which in this case, getElementById is the right method but the wrong id
document.getElementById("quote").innerHTML = finalSentence;
Looking at your HTML
<div class="quoteDisplay"><center>Your random message will be displayed here</center></div>
<div id="quote">
Looking at your javascript
document.getElementById("quoteDisplay").innerHTML=finalSentence;
It should be document.getElementById("quote").innerText = finalSentence;
I'm working on a project for a friend and he wants a pure walk cycle with only HTML/JS (no CSS). So I've tried to work it out but the image only shows up on the webpage.
It doesn't move when I press any buttons or anything at all.
Please show me where I went wrong. I'm used to using HTML and CSS but this is my first JS so I don't know many terms.
How it appears in the website:
My code (HTML + JS):
<!DOCTYPE html>
<html>
<head>
<title>Javascript Animation</title>
<script language="Javascript">
<!--
var walker = new Array(6);
var curWalker = 0;
var startWalking;
for(var i=0; i<6; i++) {
walker[i] = new Image();
walker[i].src = "walker"+i+".png";
}
function marathon() {
if(curWalker == 5) curWalker == 0;
else ++curWalker;
document.animation.src = walker[curWalker].src;
}
-->
</script>
</head>
<body>
<p><img src="walk1.png" name="animation"> </p>
<form>
<input type="button" name="walk" value="walk" onclick="startWalking=setInterval('marathon(),100);">
<input type="button" name="stop" value="stop" onclick="clearsetInterval(startwalking);">
</form>
</body>
</html>
Here it is how I did it get to work (I had to build my simple images with Paint in order to use them in the animation):
<html>
<head>
<title>Javascript Animation</title>
</head>
<body>
<p><img src="walker1.png" id="animation"> </p>
<form>
<input type="button" name="walk" value="walk" onclick="startWalking=setInterval(marathon,100);">
<input type="button" name="stop" value="stop" onclick="clearInterval(startWalking);">
</form>
<script>
var walker = [];
var curWalker = 0;
var startWalking;
for(var i=0; i<6; i++) {
walker[i] = new Image();
walker[i].src = "walker"+i+".png";
}
function marathon() {
if(curWalker == 5)
curWalker = 0;
else
++curWalker;
document.getElementById("animation").src = walker[curWalker].src;
}
</script>
</body>
</html>
I had to correct several typos/mistakes:
Put the JS just before the </body> closing tag
The first paramether of setInterval() must be a function name, so it must be marathon (you had 'marathon(); note that leading single quote)
In order to get the image to be substituted it is better to access the element though Id instead of name attribute. So I changed the image to <img src="walker1.png" id="animation"> (animation is now the Id) and accessed it through document.getElementById("animation")
Now the animation starts... but stops to the last image instead of restarting to the first.
That was because you used to check the curWalker variable instead of performing an assignment: I put curWalker = 0; instead of curWalker == 0;
Almost there. The loop is complete, but the stop button doesn't work. Two typos are preventing this to work:
clearsetInterval doesn't exist. The function to be called is clearInterval
Javascript is a case sensitive language. You use startwalking variable as a parameter, but the correct variable name is startWalking. So you have to correct the onclick event writing clearInterval(startWalking); instead of clearsetInterval(startwalking);
Your animation is now complete.
Note: as correctly noted by #Mike 'Pomax' Kamermans, nowadays you can avoid the use of onclick as you can attach events to the document (such as "click") by using document.addEventListener.
My quiz is getting caught and won’t pass through on to the next question when the right answer is given.
//loop through questions when right answer is given
function questFunc() {
"use strict";
//create array with my questions
var qArray = ["What is the answer to the sum 1 + 1?", "If I have two eggs and I drop one how many do I have left?", "What are the three primary colors?"];
var aArray = ["2", "1", "What are the three primary colors?"];
//create variables
var pageCounter = 1;
var qCounter = 0;
var aCounter = 0;
var theQuestions = document.getElementById("theQuestions");
var pageNum = document.getElementById("pageNum");
var theAnswer = document.getElementById("theAnswer").value;
if (qCounter < qArray.length) {
theQuestions.innerHTML = qArray[qCounter];
pageNum.innerHTML = pageCounter;
//not working - not allowing questions to move on when right answer is given.
if (theAnswer === aArray[aCounter]) {
qCounter++;
aCounter++;
pageCounter++;
}
} else if (qCounter >= qArray.length) {
theQuestions.innerHTML = "Well Done!";
pageNum.style.display = "none";
}
}
<div>
<h1 id="quizTitle">My JavaScript Quiz
</h1>
<p id="theQuestions">Click NEXT to start quiz..
</p>
<form id="" action="#" method="post">
<!-- Form Needs Columns -->
<div id="">
<label for="theAnswer"></label>
<input type="text" id="theAnswer" tabindex="1">
</div>
</form>
<span id="pageNum">
</span>
<button onclick="questFunc()">NEXT</button>
</div>
You're calling questFunc from the "Next" button, but all of your state is local to that function. So all of your state is recreated every time the function is called.
Instead, move the state that isn't specific to the function call out of the function. Since globals are a Bad Thing™, we'll do that by wrapping all our state (and the function) in a scoping function, and then use modern event handling to hook it up instead of onclick. (onxyz-attribute-style event handlers can only call global functions. It's one of the many reasons not to use them.)
So our scoping function, just to keep things contained, is:
(function() {
// Our code here
})();
...and our button is:
<button id="next-button">NEXT</button>
...and we hook it up using addEventListener:
document.getElementById("next-button").addEventListener("click", questFunc);
(See this answer if you need to support obsolete versions of IE.)
See the snippet for what state I moved out of the function, and see the comments for some other notes:
(function() {
"use strict";
var qArray = ["What is the answer to the sum 1 + 1?", "If I have two eggs and I drop one how many do I have left?", "What are the three primary colors?"];
var aArray = ["2", "1", "What are the three primary colors?"]; // Third answer looks like a copy-and-paste error
// We only need one counter, and let's start it at -1 because the first click
// starts the quiz
var counter = -1;
var theQuestions = document.getElementById("theQuestions");
var pageNum = document.getElementById("pageNum");
// Might as well get the answer field too
var theAnswer = document.getElementById("theAnswer");
// Hook up the button
document.getElementById("next-button").addEventListener("click", questFunc);
function questFunc() {
// Get their answer (if any)
var answer = theAnswer.value.trim(); // trim just to strip leading/trailing spaces
// If we're just starting the quiz or they answered correctly, show the next
if (counter == -1 || answer === aArray[counter]) {
counter++;
if (counter >= qArray.length) {
// Done with quiz
theQuestions.innerHTML = "Well Done!";
pageNum.style.display = "none";
} else {
// Show the now-current question
theQuestions.innerHTML = qArray[counter];
pageNum.innerHTML = (counter + 1);
}
// Always clear the answer
theAnswer.value = "";
} else {
// Incorrect answer, probably worth saying something here
}
}
})();
<div>
<h1 id="quizTitle">My JavaScript Quiz
</h1>
<p id="theQuestions">Click NEXT to start quiz..
</p>
<form id="" action="#" method="post">
<!-- Form Needs Columns -->
<div id="">
<label for="theAnswer"></label>
<input type="text" id="theAnswer" tabindex="1">
</div>
</form>
<span id="pageNum">
</span>
<button id="next-button">NEXT</button>
</div>
Your counters are within the function: "Double click next".
//loop through questions when right answer is given
var pageCounter = 1;
var qCounter = 0;
var aCounter = 0;
var qArray = ["What is the answer to the sum 1 + 1?","If I have two eggs and I drop one how many do I have left?","What are the three primary colors?"];
var aArray = ["2","1","What are the three primary colors?"];
function questFunc() {
var theQuestions = document.getElementById("theQuestions");
var pageNum = document.getElementById("pageNum");
var theAnswer = document.getElementById("theAnswer").value;
if (qCounter < qArray.length) {
theQuestions.innerHTML = qArray[qCounter];
pageNum.innerHTML = pageCounter;
//not working - not allowing questions to move on when right answer is given.
if (theAnswer === aArray[aCounter]) {
qCounter++;
aCounter++;
pageCounter++;
}
} else if (qCounter >= qArray.length) {
theQuestions.innerHTML = "Well Done!";
pageNum.style.display = "none";
}
}
<!DOCTYPE>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link rel="stylesheet" type="text/css" href="quiz-css.css" />
<link rel="stylesheet" type="text/javascript" href="quiz-css.css" />
</head>
<body onload="">
<div>
<h1 id="quizTitle">My JavaScript Quiz
</h1>
<p id="theQuestions">Click NEXT to start quiz..
</p>
<form id="" action="#" method="post">
<!-- Form Needs Columns -->
<div id="">
<label for="theAnswer"></label>
<input type="text" id="theAnswer" tabindex="1">
</div>
</form>
<span id="pageNum">
</span>
<button onclick="questFunc()">NEXT</button>
</div>
<script src="quiz-js.js"></script>
</body>
</html>
I have a page with more than 200 links with this kind of formatting.
<h1>
Somelink
some text that explain the meaning of the link.
</h1>
Now, to make it bit easy to search through this link, i have put a search box.
My requirement is to search through all this tag and find the links that are relevant to
the search box and hiding rest of the link.
How to do it in javascript ? ( i know basic javascript/jquery stuff but How to do full text search ? ) I do not required sorting according to relevant, just filter and show hide is good enough.
You can enumerate all h1 tags get inner html and do indexOf , or you can use jQuery it has a custom made contains functionality, which returns the elements having given text.
Here is an example copied from jQuery docs
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<div>John Resig</div>
<div>George Martin</div>
<div>Malcom John Sinclair</div>
<div>J. Ohn</div>
<script>
$("div:contains('John')").css("text-decoration", "underline");
</script>
</body>
</html>
Hopefully you find this useful. It probably is not the elegant or most efficient but it will let you enter multiple search terms and gives partial matches (which may or may not be wanted). The way I have made it when you click the search button it will hide all other elements except ones matching either of your search terms but you can modify this to do whatever you want with the elements in the results Array. I don't recommend using this exactly but hopefully it will give you a point of reference on how you may want to implement your own (if you choose to go with a solution other than the quicksearch).
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type='text/javascript' language='javascript' >
$(document).ready(function() {
var links = new Array();
$("h1").each(function(index, element) {
links.push({
text: $(this).text(),
element: element
});
});
$("#searchButton").click(function() {
var query = $("#searchBox").val();
var queryTerms = query.split(' ');
var results = new Array();
for(var i = 0; i < queryTerms.length; i++) {
for(var j = 0; j < links.length; j++) {
if (links[j].text.indexOf(queryTerms[i]) > -1) {
results.push(links[j].element);
}
}
}
$("h1").each(function(index, element) {
this.style.display = 'none';
});
for(var i = 0; i < results.length; i++) {
results[i].style.display = 'block';
}
});
});
</script>
</head>
<body>
<p>
<input id="searchBox" type="text" />
<input type="button" id="searchButton" value="Search" />
</p>
<h1>
Somelink1
asdf
</h1>
<h1>
Somelink2
ssss
</h1>
<h1>
Somelink3
3333
</h1>
<h1>
Somelink4
232323
</h1>
<h1>
Somelink5
fffff
</h1>
</body>
</html>
I found one.
http://github.com/riklomas/quicksearch
which uses regex for search.