I am a noob here in JS and I am doing my homework making a simple color guessing game. So far everything works as far as the criteria goes.
My only problem is that I can't figure out how to make it so that the background changes instantly upon user input (Right after clicking [OK] at the Prompt). As of now with the code below, the background changes only after clicking [OK] in the Congrats alert..I am pretty sure it's possible because my prof showed in the lecture an example he did where the background color changed right after guessing the correct color!
Also, it would be nice if any pros out there could give me suggestions on polishing my code. I have a feeling that it is messy and too complex than what its trying to achieve..Heh..
PS: I know that js logic should be separated in the page but my prof insisted we do this exercise with the script inline!
Thank you!
<body onload="doGame()">
<script>
var myBody = document.getElementsByTagName("body")[0];
var target;
var answer;
var guessInputText;
var guessInput;
var finished = false;
var guessAmount = 0;
var colors = ['Salmon', 'Tomato', 'Moccasin', 'Peru', 'Olive', 'Teal', 'Navy', 'Thistle', 'Beige', 'Gray'];
var colorsSorted = colors.sort();
var colorsSortedString = colors.join(', ');
function doGame() {
var randomColorNum = Math.random() * 10;
var randomColorNumInt = Math.floor(randomColorNum);
target = colors[randomColorNumInt + 1];
answer = target.charAt(0).toLowerCase() + target.slice(1).toLowerCase(); //makes sure answer is in lowercase
alert("The answer is " + target + " or " + answer); //for debugging
while(!finished) {
guessInputText = prompt('I am thinking of one of these colors:\n\n' +
colorsSortedString + '\n\n' +
'What color am I thinking of?');
guessInput = guessInputText.charAt(0).toLowerCase() + guessInputText.slice(1).toLowerCase(); //converts whatever input into lowercase
guessAmount += 1;
finished = checkGuess(); //checks to see if user input is correct
}
}
function checkGuess() {
if ((colors.indexOf(guessInputText.charAt(0).toUpperCase() + guessInputText.slice(1).toLowerCase()) > -1) == false) {
alert("Sorry, I don't recognize your color.\n\n" +
"Please try again!");
return false;
}
if (guessInput > answer) {
alert("Sorry, Your guess is incorrect!\n\n" +
"Hint: Your color is alphabetically higher than mine.\n\n" +
"Please try again!");
return false;
}
if (guessInput < answer) {
alert("Sorry, Your guess is incorrect!\n\n" +
"Hint: Your color is alphabetically lower than mine.\n\n" +
"Please try again!");
return false;
}
myBody.style.background = answer;
alert("Congratulations! You have guessed the color!\n\n" +
"It took you " + guessAmount + " guesses to finish the game!\n\n" +
"You can see the color in the background.");
return true;
}
</script>
</body>
If you want to modify the background before the [OK] on congrats prints, you just have to move this line
myBody.style.background = answer;
But.. Testing your snippet, the background change right after I press OK on the guess color prompt.
So what do you want exactly ? Can you give us an example step by step ?
Related
EDIT: thanks to all of you it has been fixed (: thank you soooooooo much
I cant get the alert,confirm or prompt to work, here is my code (not the full code but the beginning is the part tht I cant get to work so im leaving that and omitting the end of the code, so here it is :
var warGood = 0
var warEvil = 0
var life
var mh = false
var document.Gold = 1000;
var gems = 1000;
var lb = false
var Stellar_grenades = 0
var Cosmic_grenades = 0;
var Level = 1
var person
person = prompt("please enter your name", "Specimen")
if (person != null) {
if (person == "shit") {
alert("Really? choose a new MORE APPROPRIATE name", "Ok ill choose a new More APPROPRIATE name")
}
else if (person != "shit"){
if (person != null) {alert(
"welcome " + person + " to the universe")
}
}
alert(
"not too long ago your planet was blown up in the midst of a universal war, you luckily survived and fled to another planet");
alert("You are now here, On Planet Vecron, Here you will build up your base,")
alert("then you can eventually go on missions to distant planets,")
alert("Upon Reaching the final mission, you will notice one thing")
alert ("Your Not on a new planet, but rather a new universe,")
alert("this universe holds the Key to cosmic peace,")
alert(" This Key is the Community Pendant")
life = confirm("Do you have what it takes to get this pendant and end the universal war?")
if (life == true) {
alert("Thank you " + person + "You will make a fine adventurer");
alert("gold is the main currency Here on vecron")
alert(" If you want anything it can buy it, with a few exceptions")
alert("You cant buy the Community Pendant")
alert(" Or gems Or the special 12 summoners tools")
alert(" Shh the summoners tools will be talked about later")
alert("saving your game is important,")
alert("To Open the shop Press S")
alert("To Save Press F")
alert("To get money you simply have to press the money button!")
alert("The Ding Is to make sure you actually have good reflexes while in missions.")
alert("You get missions after you unlock the mission hall")
alert("then you can start the first journey on your many adventures")
document.write("you have " + document.Gold + " Gold and " + gems + " gems")
alert("Go Get that Pendant and save the world")
<img src = "logo.png" alt = "logo">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
I really cant figure it out, it was working fine a few weeks ago, then I took a break and came back to it and all of a sudden it wouldn't work anymore
Document.gold isn't valid JS. If you want global variables you can just use the var keyword. This will add them to the global scope. Like this:
var gold = 1000;
Document the main object of the DOM API. The HTML document is parsed and loaded into memory in a JS representation. You then can modify the DOM which will cause the UI to update. You are already doing this in the following code (changed it a bit):
var gold = 1000;
var gems = 25;
document.write("you have " + gold + " Gold and " + gems + " gems")
I'm trying to have a button and text box displayed. Have the user enter a number. That a random number will be generated and the user has 10 attempts to answer the question correctly. The script should check whether the users number is either equal to, less than, or greater than the random number. I am having trouble getting the number inputted from the text-box.
HTML:
<form name="myForm">
<div id='myForm'></div>
</form>
JAVASCRIPT:
function partC(){
var guessCount = 10;
var random = Math.round(Math.random()*100);
var button = document.createElement('input');
button.type = "button";
button.value = " Guess! ";
document.getElementById('myForm').appendChild(button);
var textbox = document.createElement('input');
textbox.type = 'number';
document.getElementById('myForm').appendChild(textbox);
var check = document.getElementById('textbox').value
button.onclick = calc(guessCount, random, check);
}
function calc(guessCount, random, check){
while(guessCount > 0) {
if (check == random){
alert("Correct!");
} else if (check > random) {
alert("Try Again. Guess to High. " + guessCount + " tries left.");
} else if (check < random) {
alert("Try Again. Guess to Low. " + guessCount + " tries left.");
}
guessCount--;
}
}
Your code is assigning callback function result to onclick event instead of function itself. Besides, you are also trying to run a while loop which will consume guessCount on first click event.
I edited code, following should work:
function partC(){
var guessCount = 10;
var random = Math.round(Math.random()*100);
var button = document.createElement('input');
button.type = "button";
button.value = " Guess! ";
document.getElementById('myForm').appendChild(button);
var textbox = document.createElement('input');
textbox.type = 'number';
document.getElementById('myForm').appendChild(textbox);
button.onclick = function(){
var check = textbox.value*1;
if (check == random){
alert("Correct!");
} else if (check > random) {
alert("Try Again. Guess to High. " + guessCount + " tries left.");
} else if (check < random) {
alert("Try Again. Guess to Low. " + guessCount + " tries left.");
}
guessCount--;
}
}
You are accessing the value by using id, whereas you didn't give any id to your input.
Try this:
textbox.id = 'textbox';
You forgot the set the id of your textbox element. Try adding the id after creating it. Then you can get the element by its id, which in your case is textbox
var myEl = document.getElementById('a');
myEl.addEventListener('click', function() {
alert(document.getElementById('text').value);
}, false);
<input type="text" id="text"/>
<button id="a">Alert text</button>
Jquery has a wonderful option available for you,
$('#unique-id').val();
The unique ID will be whatever value that specific textarea. So in this case:
<textarea id="unique-id"></textarea>
I just wanted to add this to what all the other answers say. You probably want a semicolon after this line:
var check = document.getElementById('textbox').value
I recently started learning javascrpt, but I have some experience with C#. My school gave me an old text book called Complete Concepts and Techniques(second Edition). this book was written by Shelly Cashman and Dorin Quasney... My problem is that I cant get any of the methods or functions to work. Here are 2 of my most current issues:
var scrollMsg = "Mortage rates are at their lowest!"
var msgSpace = "--- ---"
var beginPos = 0
function scrollingMsg() {
document.msgForm.scrollingMsg.value =
scrollMsg.substring(beginPos,scrollMsg.length)+msgSpace+scrollMsg.substring(0,begi
nPos)
beginPos = beginPos + 1
If (beginPos > scrollMsg.length) {
beginPos = 0
}
window.setTimeout("scrollingMsg()",200)
}
function doMort() {
document.MortCalc.Amount.value=" "
document.MortCalc.Rate.value=" "
document.MortCalc.Years.value=" "
document.MortCalc.Payment.value" "
document.MortCalc.Amount.focus()
}
The scrollingMsg() function does not work. It does not place anything in the scrollingMsg text box. So there is no message in it. My second issue is with the doMort() function. The function does clear any of the boxes nor does it set a focus. Can you please tell me what's wrong. P.S. These are not my own code. These were project codes from the txt book, but they do not work.
Try adding semicolons after each statement, and you have a typo ('If' needs to be lowercase).
I fixed the code to comply with JSLint, use this site to verify your javascript
http://www.javascriptlint.com/online_lint.php
var scrollMsg = "Mortage rates are at their lowest!";
var msgSpace = "--- ---";
var beginPos = 0;
function scrollingMsg() {
document.msgForm.scrollingMsg.value = scrollMsg.substring(beginPos,scrollMsg.length) + msgSpace + scrollMsg.substring(0,beginPos);
beginPos = beginPos + 1;
if (beginPos > scrollMsg.length) {
beginPos = 0;
}
window.setTimeout("scrollingMsg()",200);
}
function doMort() {
document.MortCalc.Amount.value=" ";
document.MortCalc.Rate.value=" ";
document.MortCalc.Years.value=" ";
document.MortCalc.Payment.value=" ";
document.MortCalc.Amount.focus();
}
This code below works in every other browser bar IE. The code basically looks lets the uder pick a card, if it has, it chooses another card that hasn't been picked, and then adds it too an array. Unfortunately its not working in IE. No console errors.
Does anyone have any ideas?
Thanks
function getCard(clicked_id)
{
$("#frontCard").animate({
height:"-=600",
width:"-=250",
},1000,'easeOutElastic');
$("#frontCard").css("opacity",0);
clicked_id = "#" + clicked_id;
$(clicked_id).animate({ opacity: 0, left: "700px" }, 'slow');
$("#frontCard").animate({
height:"+=400",
width:"+=250",
},1000,'easeOutElastic');
$("#frontCard").css("opacity",1);
var newCard= Math.floor((Math.random()*13)+1);
var newSuit= Math.floor((Math.random()*4)+1);
var currentCard;
var x=document.getElementById("pick");
var rules=document.getElementById("rules");
var kings=document.getElementById("kings");
var currentCards=document.getElementById("currentCard");
if (cardsPicked.indexOf(numbers[newCard-1] + " " + suits[newSuit-1])== -1){
if (numbers[newCard-1]=="K" && king<4){
king=king+1;
}
if(king==4){
king= "All kings found!";
alert("Fourth king picked. Down the jug!");
}
cardsPicked.push(numbers[newCard-1] + " " + suits[newSuit-1] );
for (count=0; count<cardsPicked.length; count++)
currentRule = cardRules[newCard-1];
x.innerHTML=cardsPicked;
currentCards.innerHTML=numbers[newCard-1] + " " + suits[newSuit-1];
rules.innerHTML=currentRule;
kings.innerHTML=king;
}else{
getCard();
}
}
{
height:"-=600",
width:"-=250",
}
{
height:"+=400",
width:"+=250",
}
Remove the trailing , in each of your comma separated values in Objects.
I don't see the click event. But may be it helps:
Never overwrite the running event with innerHTML (in IE <10).
I've been trying to figure this out for a while, and I'm totally stumped.
I'm writing a program that is supposed to display a basic series of multiple-choice questions. You see a question, you click one of the answers, and you move on to the next question.
The problem is, I can't figure out how to display one question, then display the next question when the user clicks one of the buttons. Nothing happens when I click a button. What's going wrong?
// progress meter
var progress = new Array();
for (var i = 0; i < questions.length; i++) progress.push("0");
var i = 0;
display(0);
// display questions
function display(i) {
var prg_string;
for (var j = 0; j < progress.length; j++) prg_string += progress[j];
document.write(
"<div id = 'background'>"
+ "<div id = 'progress'>" + progress + "</div>"
+ "<div id = 'title'>-JogNog Test v1-<br></br>" + tower + "</div>"
+ "<div id = 'question'>" + questions[i].text + "</div>"
+ "<div id = 'stats'>Level " + level + "/" + total_levels + " Question " + (i + 1) + "/" + questions.length + "</div>"
+ "</div>"
);
document.write("<button id = 'answer1' onclick = 'next(questions[i].answers[0].correct)'>" + questions[i].answers[0].text + "</button>");
if (questions[i].answers.length > 0)
document.write("<button id = 'answer2' onclick = 'next(questions[i].answers[1].correct)'>" + questions[i].answers[1].text + "</button>");
if (questions[i].answers.length > 1)
document.write("<button id = 'answer3' onclick = 'next(questions[i].answers[2].correct)'>" + questions[i].answers[2].text + "</button>");
if (questions[i].answers.length > 2)
document.write("<button id = 'answer4' onclick = 'next(questions[i].answers[3].correct)'>" + questions[i].answers[3].text + "</button>");
}
// go to next question, marking whether answer was right or wrong
function next(correct) {
if(correct) progress[i] = "T";
else progress[i] = "F";
i += 1;
display(i);
}
I haven't read through your code, (you might want to work on posting SSCCEs by focusing just on the part that handles the loop) but I get the feeling a loop is not what you want here. Loops are great if you need to automatically iterate through something. But really, you want to display only a single question at a time.
The easiest way to do this, assuming you have a means of handling each question independently, is just to keep track of which question the user is up to. Display that question. When the user submits an answer, call whatever function renders a question using the counter, plus one. Make sure to check that you haven't hit the end of the quiz so that you don't reference a question that doesn't exist.
Here's some pseudocode:
var questionNumber, questions; //assume these already have values
function printQuestion(questionNumber){ ... }
function nextQuestion(){
if(questionNumber < questions){
questionNumber++;
printQuestion(questionNumber);
}
else{
showResults();
}
}
I agree with #ngmiceli that a loop isn't what you want here. You want to display one question, and then create click event handlers that will move on to the next question when the user selects an answer to the previous question.
I went ahead and created a different setup to demonstrate. You can see a demo here:
-- jsFiddle DEMO --
But I'll walk through the process. First, I set up a basic HTML document:
<body>
<h1>-Test v1-</h1>
<h2>Simple Math</h2>
<div id="container">
<div><span id="numRight">0</span> of <span id="numQuestions">0</span></div>
<div id="question"></div>
<div id="answers"></div>
</div>
</body>
Then, I created a questions array, each element in the array being an object. Each question object contains the question itself, an array of possible answers, and an "answerIdx" property that indicates the array index of the correct answer.
questions = [
{
question: 'What is 0 / 6 ?',
options: ['0','1','2'],
answerIdx: 0
},
{
question: 'What is 2 + 2 ?',
options: ['72','4','3.5'],
answerIdx: 1
}
]
I also created some other variables that point to the HTML elements I am going to want to manipulate:
numRight = 0,
numQuestions = 0,
answerDiv = document.getElementById('answers'),
questionDiv = document.getElementById('question'),
numRightSpan = document.getElementById('numRight'),
numQuestionsSpan = document.getElementById('numQuestions');
Next, I created a 'displayQuestion' function which takes a single question object as a parameter:
function displayQuestion(q) {
// insert the question text into the appropriate HTML element
questionDiv.innerHTML = q.question;
// remove any pre-existing answer buttons
answerDiv.innerHTML = '';
// for each option in the 'options' array, create a button
// attach an 'onclick' event handler that will update
// the question counts and display the next question in the array
for(i = 0; i < q.options.length; i++) {
btn = document.createElement('button');
btn.innerHTML = q.options[i];
btn.setAttribute('id',i);
// event handler for each answer button
btn.onclick = function() {
var id = parseInt(this.getAttribute('id'),10);
numQuestionsSpan.innerHTML = ++numQuestions;
// if this is the right answer, increment numRight
if(id === q.answerIdx) {
numRightSpan.innerHTML = ++numRight;
}
// if there is another question to be asked, run the function again
// otherwise, complete the test however you see fit
if(questions.length) {
displayQuestion(questions.shift());
} else {
alert('Done! You got '+numRight+' of '+numQuestions+' right!');
}
}
answerDiv.appendChild(btn);
}
}
Finally, I displayed the first question:
displayQuestion(questions.shift());