I am wanting to create a button, and when it is pressed it will 'type' out some random text. I've followed many tutorials/code snippets with no luck in getting the implementation right.
Essentially, I want to combine these two scripts. When I click a button it should choose a random string and then use the 'typing' effect to type it.
Pressing the button again will interrupt whatever is being typed, and generate new text.
Any help is really appreciated!
var i = 0;
var txt = 'Lorem ipsum dummy text.';
var speed = 50;
function typeWriter() {
if (i < txt.length) {
document.getElementById("demo").innerHTML += txt.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
}
<button onclick="typeWriter()">Click me</button>
<p id="demo"></p>
and this:
var quotes = [
'The sky is blue',
'The stove is hot',
'The floor is wet',
'The grass is green',
'The water is cold'
]
function newQuote() {
var randomNumber = Math.floor(Math.random() * (quotes.length));
document.getElementById('quoteDisplay').innerHTML = quotes[randomNumber];
}
<div id="quoteDisplay"></div>
<button onclick="newQuote()">Click me</button>
you almost there
var i = 0;
var txt = ''; //the typing text
var speed = 50;
function typeWriter() {
//clear the html initially for a text
if (i === 0)
document.getElementById("demo").innerHTML = '';
if (i < txt.length) {
document.getElementById("demo").innerHTML += txt.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
}
var quotes = [
'The sky is blue',
'The stove is hot',
'The floor is wet',
'The grass is green',
'The water is cold'
]
function newQuote() {
//set the typing text
txt = quotes[Math.floor(Math.random() * quotes.length)];
//reset the index
i = 0;
typeWriter();
}
<button onclick="newQuote()">Click me</button>
<p id="demo"></p>
Here we go:
var i = 0;
var speed = 50;
var timeoutId;
var quotes = [
'The sky is blue',
'The stove is hot',
'The floor is wet',
'The grass is green',
'The water is cold'
]
function newQuote() {
document.getElementById("quoteDisplay").innerHTML = ""
var randomNumber = Math.floor(Math.random() *(quotes.length));
txt = quotes[randomNumber];
if (timeoutId) clearTimeout(timeoutId);
i = 0;
typeWriter(txt)
}
function typeWriter(txt) {
if (i < txt.length) {
document.getElementById("quoteDisplay").innerHTML += txt.charAt(i);
i++;
timeoutId = setTimeout(typeWriter, speed, txt);
}
}
<div id="quoteDisplay"></div>
<button onclick="newQuote()">Click me</button>
let i = 0;
let randomNumber;
let speed = 50;
let clickBtn = document.querySelector("#click");
let quotes = [
"The sky is blue",
"The stove is hot",
"The floor is wet",
"The grass is green",
"The water is cold"
];
const typeWriter = () => {
if (i === 0) {
document.getElementById("demo").innerHTML = '';
}
if (i < quotes[randomNumber].length) {
document.getElementById("demo").innerHTML += quotes[randomNumber].charAt(i);
i++;
setTimeout(typeWriter, speed);
}
};
clickBtn.addEventListener("click", () => {
i = 0
randomNumber = Math.floor(Math.random() * quotes.length);
typeWriter();
});
You should use setInterval instead:
/* js/external.js */
//<![CDATA[
var doc, bod, I, TypeMaker; // for use on other loads
addEventListener('load', function(){
doc = document; bod = doc.body;
I = function(id){
return doc.getElementById(id);
}
TypeMaker = function(element, interval){
this.element = element; this.interval = interval || 50;
var t = this, r;
this.type = function(string){
if(r)clearInterval(r);
var s = string.split(''), l = s.length, i = 0;
var p = 'value' in this.element ? 'value' : 'innerHTML';
this.element[p] = '';
r = setInterval(function(){
t.element[p] += s[i++];
if(i === l){
clearInterval(r); r = undefined;
}
}, t.interval);
}
}
var typer = new TypeMaker(I('output')), single_test = I('single_test'), rand_test = I('rand_test');
var testArray = ['The sky is blue.', 'The stove is hot.', 'The floor is wet.', 'The grass is green.', 'The water is cold.'];
var testArrayL = testArray.length;
single_test.onclick = function(){
typer.type('Lorem ipsum dummy text.');
}
rand_test.onclick = function(){
typer.type(testArray[Math.floor(Math.random()*testArrayL)]);
}
});
//]]>
/* css/external.css */
*{
box-sizing:border-box; padding:0; margin:0;
}
input{
padding:3px 5px;
}
#output{
display:inline-block; margin-left:7px;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1' />
<title>Test Template</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script type='text/javascript' src='js/external.js'></script>
</head>
<body>
<input id='single_test' type='button' value='test' />
<input id='rand_test' type='button' value='random' />
<div id='output'></div>
</body>
</html>
Related
Im trying shuffle the words on mouseover, but to shuffle a new word the previous word have be finished shuffling. This is because otherwise i will get an event.target.innerHTML of a word made up of random letters, if i mouseover the word while the alogorithm is shuffling.
How can i get over this problem, and shuffle any word on mouseover unless that specific word is allready shuffling?
var interv = 'undefined'
var canChange = false
var globalCount = 0
var count = 0
var isGoing = false
document.querySelectorAll("span").forEach((button) => button.addEventListener("mouseover", shuffleWord));
let texxt = document.querySelector('p');
console.log(texxt);
function shuffleWord(event){
let INITIAL_WORD = event.target.innerHTML;
if(isGoing) return;
var randomWord = getRandomWord(INITIAL_WORD);
event.target.innerHTML = randomWord;
isGoing = true;
interv = setInterval(function() {
var finalWord = ''
for(var x=0;x<INITIAL_WORD.length;x++) {
if(x <= count && canChange) {
finalWord += INITIAL_WORD[x]
} else {
finalWord += getRandomLetter()
}
}
event.target.innerHTML = finalWord
if(canChange) {
count++
}
if(globalCount >= 20) {
canChange = true
}
if(count>=INITIAL_WORD.length) {
clearInterval(interv)
count = 0
canChange = false
globalCount = 0
isGoing = false
}
globalCount++
},40)
function getRandomLetter() {
var alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
return alphabet[rand(0,alphabet.length - 1)]
}
function getRandomWord(word) {
var text = word;
console.log(text);
INITIAL_WORD = event.target.innerText;
var finalWord = ''
for(var i=0;i<text.length;i++) {
finalWord += text[i] == ' ' ? ' ' : getRandomLetter()
}
return finalWord
}
function rand(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<span>SOME RANDOM TEXT</span>
<br>
<br>
<span>MORE TEXT</span>
<br>
<br>
<span>EVEN MORE TEXT</span>
<script src="script.js"></script>
</body>
</html>
My goal for this experiment is to have 2 blocks of trials, both which flash 10 words and then the participants have to click yes or no if they saw the word or not (answer yes or no to 20 words). After the 2 blocks I would like the data to be displayed and the experiment to end, although right now the experiment is infinite and displays data after every block. I also need to know how to save the data with a "Save Data" button after presenting both of the blocks data at the end. Any and all help appreciated!
If anyone has any ideas about how to create two blocks, as I have tried to initiate by declaring blocks = 0 at the beginning it would be greatly appreciated!
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<script src="342.js" type="text/javascript"></script>
<script type="text/javascript">
let index = 0, blocks=0;
let words = ["fox", "tree", "wheel", "pillow", "target", "wool", "bread", "sport", "dog", "straw", "state",
"mountain", "cot" , "green" , "napkin" , "grape" , "glass" , "drum" , "grass",];
let stimuli = [];
let N = words.length/2;
let t;
window.onload = initialize;
function initialize() {
for (let i = 0; i < words.length; i++) {
stimuli.push(new Stimulus(words[i]));
}
shuffle(stimuli);
for (let i = 0; i < words.length; i++) {
if (i < N) {
stimuli[i].presented = "1";
stimuli[i].presOrder = i;
}
else {
stimuli[i].presented = "0";
stimuli[i].presOrder = "-1"
}
}
}
function Stimulus(word) {
this.word = word;
}
Stimulus.prototype.toString = function () {
return "\t Order Presented: " + this.presOrder + "\t Order tested: " + this.testOrder + "\t Word Presented:" + this.word + "\t Response (0 or 1):"
+ this.resp + " \t Presented (0 or 1):" + this.presented;
};
function begin() {
document.getElementById("b").style.visibility = "hidden";
document.getElementById("word").innerHTML = "";
t = setInterval(nextWord, 250)
}
function nextWordTest() {
document.getElementById("word").innerHTML = stimuli[index].word;
stimuli[index].testOrder = index;
if (blocks=1)
{
document.getElementById("b2").style.visibility = "visible";
}
}
function nextWord()
{
if (index < N)
{
document.getElementById("word").innerHTML = stimuli[index].word;
stimuli[index].presOrder = index;
index++;
}
else
{
clearInterval(t);
document.getElementById("word").innerHTML = "Click yes if you saw the word and " +
"no if you did not see the word";
document.getElementById("yes").style.visibility = "visible";
document.getElementById("no").style.visibility = "visible";
document.getElementById("b2").style.visibility = "hidden";
index = 0;
N = words.length;
stimuli = shuffle(stimuli);
nextWordTest();
}
}
function record(resp) {
stimuli[index].resp = resp;
index++;
if (index < N) {
nextWordTest();
}
else {
if (blocks===0){
nextWordTest()
}
if (blocks===1)
{
document.getElementById("word").innerHTML = "finished";
data = "";
for (let i = 0; i < stimuli.length; i++)
{
data += stimuli[i] + "\n";
}
console.log(data);
document.getElementById("word").innerText = data;
}
}
}
</script>
</head>
<body>
<h1> Attentional Blink Experiment </h1>
<p id="word">Push button to begin.</p>
<button type="button" id="yes" onclick="record(1)" style="visibility: hidden">yes</button>
<button type="button" id="no" onclick="record(0)" style="visibility: hidden">no</button>
<button type="button" id="b" onclick="begin()">Begin</button>
<button type="button" id="b2" onclick="begin()" style="visibility: hidden">Continue</button>
</body>
</html>
I am going through this JavaScript tutorial and ran into an issue that I hope someone can assist me with. After selecting the last question on the quiz, my showScore() function displays the results as "undefined". Through some further debugging, I found that it was a problem with my quiz object. In my PopulateQuestion() function, I am able to print out the quiz object before executing the showScore() function. However, when I attempt to print out the quiz object from within the showScore() function, it returns undefined.
I would like to work on my ability to debug issues that come up like this. Based on debugging that I have done so far, my educated guess is that this is a scope issue, but I am stuck. Does anyone have any suggestions for debugging this further?
Here is my code
Index.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>JS Quiz</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="main.css">
</head>
<body>
<div class="quiz-container">
<div id="quiz">
<h1>Star Wars Quiz</h1>
<hr style="margin-top: 20px;" />
<p id="question">Who is Darth Vader?</p>
<div class="buttons">
<button id="b0"><span id="c0"></span></button>
<button id="b1"><span id="c1"></span></button>
<button id="b2"><span id="c2"></span></button>
<button id="b3"><span id="c3"></span></button>
</div>
<hr style="margin-top: 50px" />
<footer>
<p id="progress">Question x of n</p>
</footer>
</div>
</div>
<script src="quiz-controller.js"></script>
<script src="question.js"></script>
<script src="app.js"></script>
</body>
</html>
app.js
function populateQuestion() {
if(quiz.isEnded()) {
// display score
console.log(quiz);
showScore();
} else {
// display question
var qElement = document.getElementById('question');
qElement.innerHTML = quiz.getCurrentQuestion().text;
// display choices
var choices = quiz.getCurrentQuestion().choices;
for(var i = 0; i < choices.length; i++) {
var choice = document.getElementById('c' + i);
choice.innerHTML = choices[i];
guess("b" + i, choices[i]);
}
showProgress();
}
}
function guess(id, guess) {
var button = document.getElementById(id);
button.onclick = function() {
quiz.guess(guess);
populateQuestion();
};
}
function showProgress() {
var currentQuestionNum = quiz.questionIndex + 1;
var progress = document.getElementById("progress");
progress.innerHTML = "Question " + currentQuestionNum + " of " + quiz.questions.length;
}
function showScore() {
console.log(quiz);
var resultsHTML = "<h1>Results</h1>";
resultsHTML += "<h2 id='score'>Your Score: " + quiz.getScore() + "</h2>";
var quiz = document.getElementById("quiz");
quiz.innerHTML = resultsHTML;
}
var questions = [
new Question("Who is Darth Vader?",
["Luke Skywalker", "Anakin Skywalker", "Your Mom", "Your Dad"],
"Anakin Skywalker"),
new Question("What is the name of the third episode?",
["Return of the Jedi", "Revenge of the Sith", "A New Hope", "The Empire Strikes Back"],
"Revenge of the Sith"),
new Question("Who is Anakin Skywalker's son?",
["Luke Skywalker", "Anakin Skywalker", "Your Mom", "Your Dad"],
"Luke Skywalker"),
new Question("What is the name of the sixth episode?",
["Return of the Jedi", "Revenge of the Sith", "A New Hope", "The Empire Strikes Back"],
"Return of the Jedi")
];
var quiz = new Quiz(questions);
populateQuestion();
question.js
function Question(text, choices, answer) {
this.text = text;
this.choices = choices;
this.answer = answer;
}
Question.prototype.correctAnswer = function(choice) {
return choice === this.answer;
};
quiz-controller.js
function Quiz(questions) {
this.score = 0;
this.questionIndex = 0;
this.questions = questions;
}
Quiz.prototype.getScore = function() {
return this.score;
};
Quiz.prototype.getCurrentQuestion = function() {
return this.questions[this.questionIndex];
};
Quiz.prototype.isEnded = function() {
return this.questionIndex === this.questions.length;
};
Quiz.prototype.guess = function(answer) {
if(this.getCurrentQuestion().correctAnswer(answer)) {
this.score++;
}
this.questionIndex++;
};
Your problem is that in the showScore() function you define a local variable with the name quiz. This local variable hides the global variable with the same name (even though it is defined later in the code).
You can easily fix that by renaming your local variable in showScore (below shown as q instead of quiz):
function populateQuestion() {
if(quiz.isEnded()) {
// display score
console.log(quiz);
showScore();
} else {
// display question
var qElement = document.getElementById('question');
qElement.innerHTML = quiz.getCurrentQuestion().text;
// display choices
var choices = quiz.getCurrentQuestion().choices;
for(var i = 0; i < choices.length; i++) {
var choice = document.getElementById('c' + i);
choice.innerHTML = choices[i];
guess("b" + i, choices[i]);
}
showProgress();
}
}
function guess(id, guess) {
var button = document.getElementById(id);
button.onclick = function() {
quiz.guess(guess);
populateQuestion();
};
}
function showProgress() {
var currentQuestionNum = quiz.questionIndex + 1;
var progress = document.getElementById("progress");
progress.innerHTML = "Question " + currentQuestionNum + " of " + quiz.questions.length;
}
function showScore() {
console.log(quiz);
var resultsHTML = "<h1>Results</h1>";
resultsHTML += "<h2 id='score'>Your Score: " + quiz.getScore() + "</h2>";
var q = document.getElementById("quiz");
q.innerHTML = resultsHTML;
}
var questions = [
new Question("Who is Darth Vader?",
["Luke Skywalker", "Anakin Skywalker", "Your Mom", "Your Dad"],
"Anakin Skywalker"),
new Question("What is the name of the third episode?",
["Return of the Jedi", "Revenge of the Sith", "A New Hope", "The Empire Strikes Back"],
"Revenge of the Sith"),
new Question("Who is Anakin Skywalker's son?",
["Luke Skywalker", "Anakin Skywalker", "Your Mom", "Your Dad"],
"Luke Skywalker"),
new Question("What is the name of the sixth episode?",
["Return of the Jedi", "Revenge of the Sith", "A New Hope", "The Empire Strikes Back"],
"Return of the Jedi")
];
function Question(text, choices, answer) {
this.text = text;
this.choices = choices;
this.answer = answer;
}
Question.prototype.correctAnswer = function(choice) {
return choice === this.answer;
};
function Quiz(questions) {
this.score = 0;
this.questionIndex = 0;
this.questions = questions;
}
Quiz.prototype.getScore = function() {
return this.score;
};
Quiz.prototype.getCurrentQuestion = function() {
return this.questions[this.questionIndex];
};
Quiz.prototype.isEnded = function() {
return this.questionIndex === this.questions.length;
};
Quiz.prototype.guess = function(answer) {
if(this.getCurrentQuestion().correctAnswer(answer)) {
this.score++;
}
this.questionIndex++;
};
var quiz = new Quiz(questions);
populateQuestion();
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>JS Quiz</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="main.css">
</head>
<body>
<div class="quiz-container">
<div id="quiz">
<h1>Star Wars Quiz</h1>
<hr style="margin-top: 20px;" />
<p id="question">Who is Darth Vader?</p>
<div class="buttons">
<button id="b0"><span id="c0"></span></button>
<button id="b1"><span id="c1"></span></button>
<button id="b2"><span id="c2"></span></button>
<button id="b3"><span id="c3"></span></button>
</div>
<hr style="margin-top: 50px" />
<footer>
<p id="progress">Question x of n</p>
</footer>
</div>
</div>
<script src="quiz-controller.js"></script>
<script src="question.js"></script>
<script src="app.js"></script>
</body>
</html>
There is private variable quiz in showScore
function which is getting hoisted to the top of the
function as follows:
Your code:
function showScore() {
console.log(quiz);
var resultsHTML = "<h1>Results</h1>";
resultsHTML += "<h2 id='score'>Your Score: " + quiz.getScore() + "</h2>";
var quiz = document.getElementById("quiz");
What internally happens:
function showScore() {
var quiz = undefined; // hoisting is happening here. So quiz is not reffering to public quiz variable anymore.
console.log(quiz);
var resultsHTML = "<h1>Results</h1>";
resultsHTML += "<h2 id='score'>Your Score: " + quiz.getScore() + "</h2>";
var quiz = document.getElementById("quiz");
I am new to the programming world and have been working on a trivia-game style project. The problem I am encountering is as follows: "Uncaught ReferenceError: answer is not defined at HTMLButtonElement.button.onclick".
My question is as follows: How are my question answers not being stored when pressing an answer and what is a better way to define answer in my code? Any help would greatly be appreciated.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Trivia Game</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" />
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<link href="https://fonts.googleapis.com/css?family=Lora" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="assets/css/style.css" />
</head>
<body>
<div class="grid">
<div id="trivia">
<h1>A Golfer's Trivia</h1>
<!-- for question -->
<div id="questionName">
<p id="question"></p>
</div>
<p id="progress"></p>
<!-- options for the questions -->
<div class="buttons">
<button id="btn0"><span id="option0"></span></button>
<button id="btn1"><span id="option1"></span></button>
<button id="btn2"><span id="option2"></span></button>
<button id="btn3"><span id="option3"></span></button>
</div>
<div>
<p id="timer"></p>
<p id="show-clock"></p>
</div>
</div>
</div>
<script type="text/javascript" src="assets/javascript/game.js"></script>
</body>
</html>``
JAVASCRIPT
// Keeping score
var unanswered = 0;
var questionIndex = 0;
var score = 0;
var questions = 0;
var answer;
function Quiz(questions) {
this.score = 0;
this.questions = questions;
this.questionIndex = 0;
}
function getQuestionIndex() {
return this.questions[this.questionIndex];
}
function endGame() {
return this.questions.length === this.questionIndex;
}
function guess(answer) {
if (this.getQuestionIndex() === correctAnswer(answer)) {
this.score++;
}
this.questionIndex++;
}
// functions for questions
function Question(text, choices, answer) {
this.text = text;
this.choices = choices;
this.answer = answer;
}
// check user answer
function correctAnswer(choice) {
return choice === this.answer;
}
// have questions appear if game is still going
function populate() {
console.log("populating");
if (endGame()) {
showScores();
}
else {
var element = document.getElementById("question");
element.innerHTML = getQuestionIndex().text;
// have options appear for each question
var choices = getQuestionIndex().choices;
for (var i = 0; i < choices.length; i++) {
var element = document.getElementById("option" + i);
element.innerHTML = choices[i];
guess("btn" + i, choices[i]);
}
showProgress()
}
}
// store user guess
function guess(id) {
var button = document.getElementById(id);
button.onclick = function () {
questionIndex++;
populate();
guess(answer);
}
}
// show which question player is on
function showProgress() {
var currentQuestionNumber = questionIndex + 1;
var element = document.getElementById("progress");
element.innerHTML = "Question " + currentQuestionNumber + " of " + questions.length;
}
// display scores at end of game
function showScores() {
var gameOver = "<h1>Results</h1>" + "<h2 class='corr score'> Correct Answers: " + score + "<h2>" + "<br>" + "<h2 class = 'wrong score'>Wrong Answers: " + (questions.length - score) + "<h2 class = 'unanswered score'>Unanswered: " + "<h2>";
var results = document.getElementById("trivia");
results.innerHTML = gameOver;
}
// sets of questions, options, answers
var questions = [
new Question("Where was the game of golf originally founded?",
["Scotland", "China", "England", "United States"],
"Scotland"),
new Question("Who is the only female golfer to make a cut at a PGA Tour event?",
["Michelle Wie", "Annika Sorensteim", "Lexi Thompson", "Babe Zaharias"],
"Babe Zaharias"),
new Question("What is the name for a hole-in-one on a par five?",
["Triple Eagle", "Double Ace", "Condor", "Albatross"],
"Condor"),
new Question("Who holds the record for the most PGA Tour victories?",
["Tiger Woods", "Jack Nicklaus", "Ben Hogan", "Sam Snead"],
"Sam Snead"),
new Question("What percentage of golfers will never achieve a handicap of 18 or less?",
["50 percent", "73 percent", "80 percent", "91 percent"],
"80 percent"),
new Question("How many dimples are on a standard regulation golf ball?",
["336", "402", "196", "468"],
"336"),
new Question("Who was considered the first professional golfer in history?",
["Bobby Jones", "Byron Nelson", "Walter Hagen", "Old Tom Morris"],
"Walter Hagen"),
new Question("Who is the youngest player to win the Masters?",
["Tiger Woods", "Jack Nicklaus", "Jordan Speith", "Arnold Palmer"],
"Tiger Woods")
];
populate();
var intervalId;
$("#btn").on("click", run);
// The run function sets an interval
function run() {
clearInterval(intervalId);
}
var timeLeft = 10;
var displayClock = document.getElementById('timer');
var timerId = setInterval(countdown, 1000);
function countdown() {
if (timeLeft === 0) {
unanswered++;
questionIndex++;
populate();
alert("You did not answer in time!");
timeLeft = 10;
// reset timer, pull question
run();
} else {
displayClock.innerHTML = timeLeft + ' seconds remaining';
timeLeft--;
}
}
run();
I guess you're facing another problem here. Here are 2 functions taken off your script:
guess(any) version 1
function guess(answer) {
if (this.getQuestionIndex() === correctAnswer(answer)) {
this.score++;
}
this.questionIndex++;
}
guess(any)version 2
function guess(id) {
var button = document.getElementById(id);
button.onclick = function () {
questionIndex++;
populate();
guess(answer);
}
}
You have 2 of a function named guess(). Although the names of both values vary, from Javascript's standpoint they both look like this:
function guess(value){}
How is JS supposed to know which of them you intend to call?
Rename at least one of them in order to having total unambiguousness among your function names. And try again.
I have worked for a while on this code for learning purposes. I finally got the program to work, however when you "roll the dice", it only allows the dice to be rolled 1 time; If you wish to roll the dice a second time you must refresh the screen.
I am trying to build a reset function for this program so that I can roll the dice as many times as I wish without a screen-refresh.
I have built the reset function, but It is not working... It clear's the DIV's, but doesn't allow the program to be executed again.
Can someone please help me out?
*I am a semi-noobie at Javascript, I am making programs like this to practice my skills.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dice Rolling</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<header>
<h1>Roll the Dice!</h1>
<h2>By: Jeff Ward</h2>
</header>
<h3>Setup your Dice!</h3>
<div id="left">
<form id="numberOfDiceSelection">
Number Of Dice Used:
<br>
<input id="numberOfDice" type="text" name="numberOfDice">
</form>
</div>
<div id="right">
<form id="diceSidesSelection">
Number of sides on each dice:
<br>
<input id="diceSides" type="text" name="diceSides">
</form>
</div>
<button type="button" onclick="roll()">Roll the Dice!</button>
<button type="button" onclick="reset()">Reset Roll</button>
<div id="output">
</div>
<div id="output1">
</div>
<script src="js/script.js"></script>
</body>
</html>
JavaScript:
function roll() {
var text = "";
var sides = +document.getElementById("diceSides").value;
var dice = +document.getElementById("numberOfDice").value;
var rolls = [];
// --------Ensures both Numbers are Intergers-----------
if (isNaN(sides) || isNaN(dice)) {
alert("Both arguments must be numbers.");
}
// --------Loop to Print out Rolls-----------
var counter = 1;
do {
roll = Math.floor(Math.random() * sides) + 1;
text += "<h4>You rolled a " + roll + "! ----- with dice number " + counter + "</h4>";
counter++;
rolls.push(roll);
}
while (counter <= dice)
document.getElementById("output").innerHTML = text;
// --------Double Determination-----------
var cache = {};
var results = [];
for (var i = 0, len = rolls.length; i < len; i++) {
if (cache[rolls[i]] === true) {
results.push(rolls[i]);
} else {
cache[rolls[i]] = true;
}
// --------Print amount of Doubles to Document-----------
}
if (results.length === 0) {} else {
document.getElementById("output1").innerHTML = "<h5> You rolled " + results.length + " doubles</h5>";
}
}
// --------RESET FUNCTION-----------
function reset() {
document.getElementById("output1").innerHTML = "";
document.getElementById("output").innerHTML = "";
document.getElementById("diceSides").value = "";
document.getElementById("numberOfDice").value = "";
text = "";
rolls = [];
}
Thank you!!
JSFiddle Link = https://jsfiddle.net/kkc6tpxs/
I rewrote and did what you were trying to do:
https://jsfiddle.net/n8oesvoo/
var log = logger('output'),
rollBtn = getById('roll'),
resetBtn = getById('reset'),
nDices = getById('numofdices'),
nSides = getById('numofsides'),
dices = null,
sides = null,
rolls = [],
doubles=0;
rollBtn.addEventListener('click',rollHandler);
resetBtn.addEventListener('click', resetHandler);
function rollHandler() {
resetView();
sides = nSides.value;
dices = nDices.value;
doubles=0;
rolls=[];
if(validateInput()) {
log('invalid input');
return;
}
//rolling simulation
var rolled;
while (dices--) {
rolled = Math.ceil(Math.random()*sides);
log('For Dice #'+(dices+1)+' Your Rolled: '+ rolled +'!');
rolls.push(rolled);
}
//finding doubles
//first sort: you can use any way to sort doesnt matter
rolls.sort(function(a,b){
return (a>b?1:(a<b)?0:-1);
});
for (var i =0; i < rolls.length; i++) {
if (rolls[i] == rolls[i+1]) {
doubles++;
i++;
}
}
if (doubles>0) log("You rolled " + doubles + " doubles");
}
function resetHandler(){
resetView();
nDices.value = nSides.value = '';
}
function resetView() {
getById('output').innerText = '';
}
function validateInput(){
return (isNaN(sides) || sides == '' || isNaN(dices) || dices == '');
}
function logger(x) { var output = getById(x);
return function(text){
output.innerText += text + '\n';
};}
function getById(x){ return document.getElementById(x); }