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;
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.
I have 2 html files connected to one js file. When I try to access a html element in the second html file using js it doesn't work saying that is is null. I did
let elementname = document.getElementById("element") for a element in the second html page then
console.log(elementname) and it says it is null. When I do it for a element in the first html page it says HTMLButtonElement {}
Here is the html for the first Page
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Not Quuuuiiiizzzz</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>Not Quuuuiiiizzzz</h1>
<h2>Join a quiz</h2>
<!--Buttons -->
<div style="text-align: center;">
<button id="btnforquiz1" onclick="gotoquiz()"></button>
<button id="btnforquiz2" onclick="gotoquiz1()"></button>
<button id="btnforquiz3" onclick="gotoquiz2()"></button>
</div>
<h2 id="h2">Create a Quuuuiiiizzzz</h2>
<script src="script.js"></script>
</body>
</html>
For the second page
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Not Quuuuiiiizzzz</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body onload="quizLoad()">
<h1 id="question">Hello</h1>
<button id="answer1"></button>
<button id="answer2"></button>
<button id="answer3"></button>
<button id="answer4"></button>
<script src="script.js"></script>
</body>
</html>
And Finally for the js file :
//setting global variables
let btn1 = document.getElementById("btnforquiz1") //getting button with id of btnforquiz1 repeat below
correct = 0
let btn2 = document.getElementById("btnforquiz2")
let btn3 = document.getElementById("btnforquiz3")
let question = document.getElementById("question")
let answer1 = document.getElementById("answer1")
let answer2 = document.getElementById("answer2")
let answer3 = document.getElementById("answer3")
let answer4 = document.getElementById("answer4")
quizNameRel = -1;
cosnole.log(question)
console.log(answer1)
//Quiz Data
Quiz_1 = {
"What is the capital of buffalo":["Idk", "Yes", "No",0],
"What is the smell of poop": ["Stinky"]
};
Quiz_2 = [
"What is wrong with you"
];
Quiz_3 = [
"What is wrong with you #2"
]
let quiz = {
name: ["History Test", "Math Practice", "ELA Practice"],
mappingtoans: [0,1,2],
QA: [Quiz_1, Quiz_2, Quiz_3]
}
//quiz data
//when body loades run showQuizzs function
document.body.onload = showQuizzs()
function showQuizzs() {
//loops throo the vals seeting the text for the btns
for (let i = 0; i < quiz.name.length; i++) {
btn1.textContent = quiz.name[i-2]
btn2.textContent = quiz.name[i-1]
btn3.textContent = quiz.name[i]
}
}
//leads to the showQuizzs
function gotoquiz() {
location.href = "quiz.html"
quizNameRel = quiz.name[0]//I was trying to create a relation so we could knoe which quiz they wnt to do
startQuiz()
}
function gotoquiz1() {
location.href = "quiz.html"
quizNameRel = quiz.name[1]
startQuiz()
}
function gotoquiz2() {
location.href = "quiz.html";
quizNameRel = quiz.name[2];
startQuiz();
}
function answerselect(elements){
whichone = Number(elements.id.slice(-2,-1))
if(Quiz_1[whichone]==Quiz_1[-1]){
correct+=1;
NextQuestion();
}else{
wrong+=1;
}
}
//gets the keys and puts it into an array
function getkeys(dictionary){
tempdict = [];
for(i in dictionary){
tempdict.push(i);
}
return tempdict;
}
function setQuestion() {
let tempdict = getkeys(Quiz_1)
console.log(tempdict, getkeys(Quiz_1));
//question.innerHTML = tempdict;
}
// startQuiz
function startQuiz() {
switch (quizNameRel){
case quiz.name[0]:
//case here
setQuestion()
break
case quiz.name[1]:
//case here
break
case quiz.name[2]:
//case here
break
}
}
//TO DO:
// Set the question
// Set the answer
// Check if correct button
This is happening because at a time you have rendered only one html file. For example if you render index1.html(first file) then your js will look for rendered element from first file only but here index2.html(second file) is not rendered so your js script is unable to find elements of that file that's the reason it shows null.
If you try to render now index2.html rather than index1.html then you will find now elements from index2.html are detected by js script but elements from index1.html are null now.
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).
I have a small data store of quotes like this:
let quotes = [{
quote: "Search others for their virtues, thyself for thy vices.",
source: "Benjamin Franklin",
citation: "Poor Richard\'s Almanac",
category: "ethics",
year: ''
}, {
quote: "He who has courage despises the future.",
source: "Napoleon Bonaparte",
citation: '',
category: "boldness",
year: ''
}
]
I am running a simple javascript function to change the html based on the data store with this:
const getRandomQuote = () => {
let quoteShownArr = [];
let quoteIndex = Math.floor((Math.random() * quotes.length) + 1);
for (let i = 0; i < quotes.length; i++) {
if (quoteIndex === i) {
document.getElementsByTagName("P")[0].innerHTML = quotes[i].quote;
document.getElementsByTagName("P")[1].innerHTML = quotes[i].source;
let citation = quotes[i].citation;
if(citation) {
console.log(citation);
document.getElementById("citation").innerHTML = quotes[i].citation;
}
document.getElementById("year").innerHTML = quotes[i].year;
}
}
}
getRandomQuote();
All the html elements are being updated except for my citation and year, which are span elements. I get the following error:
TypeError: "Cannot set property 'innerHTML' of null
at getRandomQuote" But the exact value consoles easily. How is this not changing the element??
Thanks.
HTML added:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Random Quotes</title>
<link href='https://fonts.googleapis.com/css?family=Playfair+Display:400,400italic,700,700italic' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<div class="container">
<div id="quote-box">
<p class="quote">You can do anything but not everything</p>
<p class="source">David Allen<span class="citation" id="citation">Making It All Work</span><span class="year" id="year">2009</span></p>
</div>
<button id="loadQuote">Show another quote</button>
</div>
<script src="js/script.js"></script>
</body>
</html>
in this line
document.getElementsByTagName("P")[1].innerHTML = quotes[i].source;
you set the inner html to the source text, removing all other html content e.G your spans, this is why they are null because they dont exist anymore
Why does this work
app.prints(address,list.options[list.selectedIndex].value);
but this doesn't?
app.prints(status,macAddress);
JavaScript
var hey = 5;
var app = {
createList: function () {
for (var i = 0; i < 5; i++) {
list.options[i] = new Option(hey + i, "mac" + i);
}
app.prints(address, list.options[list.selectedIndex].value);
},
prints: function (location, message) {
location.innerHTML = message;
},
manageConnection: function () {
var macAddress = list.options[list.selectedIndex].value;
app.prints(status, macAddress);
}
}
HTML
<!DOCTYPE html>
<!-- Don't panic! All this
code looks intimidating but eventually it will make sense. -->
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="ECMA.js"></script>
<title>My LCD code</title>
</head>
<body onload="app.initialize();">
<p>Welcome to the LCD software</p>
<select id="list" onchange="app.prints
(address,list.options[list.selectedIndex].value);"></select>
<div id="address"></div>
<button id="connect" onclick="app.manageConnection();">Connect</button>
<div id="status">hi</div>
</body>
</html>
The difference is that a global status variable has already been defined by the browser to represent the text in the status bar. And, browsers don't allow a reference to the element to replace it.
To avoid the naming conflict, you can rename the element.
But, you really shouldn't depend on automatic globals for ids. Not all browsers implement the feature, and some only in certain modes.
var list = document.getElementById('list');
var address = document.getElementById('address');
app.prints(address, list.options[list.selectedIndex].value);