Using this code to create a simple math quiz. I have button's that are set string values for both the button's text and . The issue I'm currently, is having the setter properly the button's class value after evaluating it's key value.
Inside my setStatusClass. I used if's to check the object's key values for correct. I used debugger to see if the values were even being checked. And, they are. But, I'm understand the blocks aren't being ran.
// This document, when the start button is clicked, shows questions, & starts the timer
var startButton = document.getElementById("start-btn");
var questionContainerEl = document.getElementById("question-container");
var startScreen = document.getElementById("start-screen");
var questionTitle = document.getElementById("question");
var choiceButtons = document.getElementById("choice-buttons");
//var buttonVal = 0;
var score = 0;
var shuffleQuestions, currentQindex;
var i = 0;
//Object Container to hold questions and answers
const questions = [{
question: "What is 2 + 2?",
answers: [
{text: "4", correct: "true"},
{text: "2", correct: "false"},
{text: "3", correct: "false"},
{text: "5", correct: "false"}
]
},
{
question: "What is 4*4?",
answers: [{text: '8', correct: "false"},
{text: '16',correct: "true"},
{text: '2', correct: "false"},
{text: '6', correct: "false"},
]
},
{
question: "Solve for x. y = 3x - 6",
answers: [{text: '6', correct: "false"},
{text: '3', correct: "false"},
{text: '2', correct: "true"},
{text: "idk", correct: "false"}]
}];
startButton.addEventListener('click',startGame);
//Start game function shows Question Cont. Shuffles Questions on an Arr.
function startGame() {
startScreen.classList.add('hide');
shuffleQuestions = questions.sort(() => Math.random() - .5);
currentQindex = 0;
questionContainerEl.classList.remove('hide');
setNextQuestion();
}
//Erases question and finds next one on Arr.
function setNextQuestion() {
resetState();
showQuestion(shuffleQuestions[currentQindex]);
}
//Shows question as well as answers.
function showQuestion(questions){
questionTitle.innerText = questions.question;
var ansLength = Object.keys(questions.answers).length;
var ans;
for(i = 0; i < ansLength; i++) {
//When the answer button is selected questions goes to next object element
ans = questions.answers[i];
var button = document.createElement("button");
button.innerText = ans.text;
button.classList.add('btn');
if(ans.correct === "true") {
button.correct = ans.correct;
}
button.addEventListener("click", selectAnswer);
choiceButtons.appendChild(button);
}
}
//removes buttons from choices.
function resetState() {
while(choiceButtons.firstChild) {
choiceButtons.removeChild(choiceButtons.firstChild);
}
}
function selectAnswer(e) {
//setStatusClass(document.body, isCorrect);
var ar = Array.from(choiceButtons.children);
for (buttons of ar) {
var selectedButton = e.target;
var isCorrect = selectedButton.dataset.correct;
setStatusClass(buttons, isCorrect);
}
}
function setStatusClass(element) {
clearStatusClass(element);
if (element.classList.correct == "true") {
element.classList.add("right");
}
if (element.classList.correct == "false") {
element.classList.add("incorrect");
}
}
function clearStatusClass(element){
element.classList.remove("right");
element.classList.remove("incorrect");
}
*, *::before, *::after {
box-sizing: border-box;
font-family: "Comic Sans MS", cursive, sans-serif;
font-weight: 500;
}
body {
padding: 0;
margin: 0;
display: flex;
width: 100vw;
height: 100vh;
justify-content: center;
align-items: center;
background-color: #b3d7ff;
}
.start-screen {
display:flex;
justify-content: center;
align-items: center;
}
.start-btn {
font-size: 1.5rem;
font-weight: bold;
padding: 10px 20px;
}
.btn-grid {
display: grid;
grid-template-columns: repeat(2,auto);
}
.btn {
border: black;
background-color: #b3d7ff;
border-radius: 10px;
padding: 5px 10px;
color: white;
outline: dashed;
margin: 5px;
}
.btn.right {
background-color: lightgreen;
color:black
}
.btn.incorrect {
background-color: red;
color:black;
}
.btn:hover{
border-color: black;
}
.wrapper {
width: 800px;
max-width: 80%;
background-color: white;
border-radius: 5px;
padding: 10px;
box-shadow: 0 0 10px 2px;
}
.scores {
float:left;
align-self: flex-start;
position: absolute;
}
.timer {
float:left;
align-self: flex-start;
}
.container {
width: 800px;
max-width: 80%;
background-color: white;
border-radius: 5px;
padding: 10px;
box-shadow: 0 0 10px 2px;
}
.hide {
display: none;
}
#question {
width: 700px;
max-width: 80%;
padding: 5px;
border: 2px;
text-align: center;
margin-top: 5px;
margin-bottom: 2px;
margin-left: 75px;
margin-right: 75px;
}
<!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>The Quiz</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="./Assets/css/style.css" type = "text/css" media= "screen">
</head>
<body>
<div class="scores">View Highscores</div>
<div class="timer">Time: <span id="time">0</span></div>
<div class="wrapper">
<div id="start-screen" class="start">
<h1>The Quiz</h1>
<p>
This quiz is on a timer. Please do your best to complete it before the timer runs out.
Keep in mind that wrong answers will penalize you.
</p>
<button id="start-btn" class = "start-btn btn?">Start the Quiz</button>
</div>
<div id= "question-container" class= "hide">
<div id="question">Question</div>
<div id="choice-buttons" class= "btn-grid">
<button class= "btn hover">Answer 1</button>
<button class= "btn hover">Answer 2</button>
<button class= "btn hover">Answer 3</button>
<button class= "btn hover">Answer 4</button>
</div>
</div>
<div id="final-screen" class= "hide">
<h2>You're finished</h2>
<p>Your final score is<span id="final-score"></span>.</p>
<p>
Enter intials: <input type="text" id="initals" max="3" />
<button id="submit">Submit</button>
</p>
</div>
</div>
<script defer src="./Assets/js/logic.js"></script>
<script defer src="./Assets/js/questions.js"></script>
</body>
</html>
The way to tell if a class is in an element's class list is with the .includes() method.
function setStatusClass(element) {
clearStatusClass(element);
if (element.classList.includes("correct")) {
element.classList.add("right");
} else {
element.classList.add("incorrect");
}
}
Related
I created a constructor function name Book and an empty array named myLibrary as a container for these new book object instances. A separate function to create a book createBook calls a function addBookToLibrary which pushes the book into the myLibrary array, clears the form to add books, then renders the book list via the viewBookList function.
Each time I call createBook and create a new instance of Book, I'm running into a problem where the rendered list of books that show up on the page repeat all instances of Book objects created prior to the new book being added plus the one new book. For instance, I have book1, book2 and book3 that I previously created. I then add book4 so now the array has [ {book1...}, {book2...}, {book3...}, {book4...} ] objects correctly in place, but what's being rendered on the page is a scattered mess of book1, book1, book2, book1, book2, book3, book1, book2, book3, book4 as you see in the attached image. You'll see the array in the console is fine.
I initially cleared out the myLibrary array in createBook which correctly rendered the books to the page, but obviously wipes out my array which won't work because I need to be able to delete these at some point from the array. So my question is, how do I display what's in my array onto the page each time without rendering duplicates of books that were already added?
const submitButton = document.querySelector('#submit');
const btnOpenModal = document.querySelector('.open-modal');
const btnCloseModal = document.querySelector('.close-modal');
const modalElement = document.querySelector('.modal');
// let myLibrary = [
// new Book('Down and Out in Paris and London', 'George Orwell', 232, true),
// new Book('Homage to Catalonia', 'George Orwell', 202, true),
// new Book('Shooting an Elephant', 'George Orwell', 368, false),
// ];
// let count = myLibrary.length - 3;
let myLibrary = [];
let count = myLibrary.length;
// Constructor...
function Book(title, author, pages, read) {
this.title = title;
this.author = author;
this.pages = Number(pages);
this.read = Boolean(read);
// Methods
this.bookInfo = function () {
const wasRead = this.read === true ? 'read' : 'not read';
return `${this.title} written by ${this.author}, ${this.pages} pages in length was ${wasRead}.`;
};
return this.bookInfo();
}
function createBook(e) {
e.preventDefault();
// myLibrary = [];
let title = document.querySelector('#title').value;
let author = document.querySelector('#author').value;
let pages = document.querySelector('#pages').value;
let read = document.querySelector('#read').value;
// Instantiate new Book object
const newBook = new Book(title, author, pages, read); // Add ID when instantiating
addBookToLibrary(newBook);
clearForm();
viewBookList(myLibrary);
}
function addBookToLibrary(book) {
// Hide modal
removeClass();
// Add book to array
return myLibrary.push(book);
}
function clearForm() {
document.querySelector('#form').reset();
}
function setCardStyle(element, details) {
element.setAttribute(
'style',
'display: flex; flex-direction: column; justify-content: space-between; text-align: center; background-color: #fff; padding: 1em; margin: 1em 1em 1em 0; border-radius: 5px; height: 250px; width: 250px; line-height: 1.5; box-shadow: 0 5px 10px 2px rgba(0, 0, 0, 0.2);',
);
element.innerHTML = `
<h3 class="title">${details.title}</h3>
<br>
<hr>
<br>
<p>${details.author}</p>
<p>${details.pages} pages</p>
<p>${details.read === true ? 'Read' : 'Unread'}</p>`;
}
function createCard() {
let bookCard = document.createElement('div');
bookCard.classList.add('card');
bookCard.setAttribute('data-target', `${count++}`); // Set target ID
return bookCard;
}
function removeBookBtn() {
let btn = document.createElement('button');
// Style button
btn.setAttribute(
'style',
'color: red; height: 2.5em; width: 50%; border-radius: 5px; margin: 0 auto; font-weight: bold; text-transform: uppercase; cursor: pointer;',
);
btn.innerHTML = 'Delete';
return btn;
}
function handleDelete(e) {
// Get book's data-target
let bookIndex = parseInt(e.path[1].attributes[1].value);
// console.log(bookIndex);
myLibrary.splice(bookIndex, 1);
// console.log(newArray);
// myLibrary = myLibrary.filter((book, index) => index !== bookIndex);
return viewBookList(myLibrary);
}
function clearDOM(element) {
while (element.firstElementChild) {
element.firstElementChild.remove();
}
}
function viewBookList(list) {
const bookDiv = document.querySelector('.book-list');
clearDOM(bookDiv);
for (book in list) {
let bookDetails = list[book];
let renderCard = createCard();
const deleteButton = removeBookBtn();
deleteButton.addEventListener('click', handleDelete);
setCardStyle(renderCard, bookDetails);
renderCard.appendChild(deleteButton);
bookDiv.appendChild(renderCard);
}
return bookDiv;
}
function addClass() {
return modalElement.classList.add('open');
}
function removeClass() {
return modalElement.classList.remove('open');
}
// Event listeners
btnOpenModal.addEventListener('click', addClass);
btnCloseModal.addEventListener('click', removeClass);
submitButton.addEventListener('click', createBook);
#import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap');
:root {
--roboto: 'Roboto', sans-serif;
--pt: "PT Sans", sans-serif;
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
html {
font-family: var(--roboto);
}
body {
min-height: 100vh;
display: flex;
justify-content: center;
background-image: linear-gradient(to top, #a6c1ee 0%, #fbc2eb 100%);
}
.header {
text-align: center;
}
.header h1 {
color: #fff;
font-size: 4rem;
text-shadow: 1px 2px 5px #000;
}
.modal {
padding: 1em;
background-color: #fff;
}
.label {
text-transform: capitalize;
}
.btn {
font-family: "PT Sans", sans-serif;
font-size: 1.2rem;
padding: 1rem 2.5rem;
cursor: pointer;
border: none;
}
.modal {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
align-items: center;
justify-content: center;
background: rgba(0, 0, 0, 0.7);
}
.open-modal {
background: #fff;
border-radius: 5px;
box-shadow: 0 5px 10px 2px rgba(0, 0, 0, 0.2);
transition: all 0.2s linear;
}
.open-modal:hover {
box-shadow: none;
background: rgba(255, 255, 255, 0.8);
}
.modal.open {
display: flex;
}
.form {
padding: 5em;
}
.modal-container {
background-color: #fff;
width: 90%;
max-width: 450px;
position: relative;
}
.modal.open .modal-container {
animation: move 0.6s ease-out;
}
#keyframes move {
from {
transform: translateY(-50px);
}
to {
transform: translateY(0px);
}
}
.close-modal {
font-size: 3rem;
position: absolute;
top: 0;
right: 0;
background-color: #fff;
height: 40px;
width: 40px;
text-align: center;
line-height: 40px;
cursor: pointer;
transition: color 0.15s linear;
}
.close-modal:hover {
color: #f00;
}
.book-list {
display: flex;
flex-wrap: wrap;
margin-top: 1.5em;
gap: 2em;
}
/* Created in app.js */
/* .card {
} */
<!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">
<link rel="stylesheet" href="styles/style.css">
<script src="scripts/app.js" defer></script>
<title>Odin Library</title>
</head>
<body>
<div class="container">
<header class="header">
<h1>Library</h1>
</header>
<section class="modal open">
<div class="modal-container">
<span id="close-modal" class="close-modal">×</span>
<form action="" method="POST" name="bookForm" id="form" class="form">
<div class="form-row">
<label for="title" class="label">title: </label>
<input type="text" name="title" id="title" placeholder="Animal Farm" required>
</div>
<div class="form-row">
<label for="author" class="label">author: </label>
<input type="text" name="author" id="author" placeholder="George Orwell" required>
</div>
<div class="form-row">
<label for="pages" class="label">pages: </label>
<input type="number" name="pages" id="pages" placeholder="232" required>
</div>
<div class="form-row">
<label for="read" class="label">read: </label>
<input type="checkbox" name="read" id="read" required>
</div>
<div class="button-container">
<input type="submit" value="Create" id="submit" class="submit">
</div>
</form>
</div>
</section class="card-section">
<section>
<!-- Add plus icon -->
<button class="btn open-modal" id="open-modal">Add Book</button>
<div class="book-list">
<!-- Container for cards -->
</div>
</section>
</div>
</body>
</html>
Like the others already said on the comment, the problem is that each time you add a new book, when you try to display ti on the page you are "appending" all the books after the already existing books.
So you get something like this:
Add book 1: (1)
Add book 2: (1) (1 2)
Add book 3: (1) (1 2) (1 2 3)
The solution is to clear the container div before you update it.
Something like this (JS line 107):
const submitButton = document.querySelector('#submit');
const btnOpenModal = document.querySelector('.open-modal');
const btnCloseModal = document.querySelector('.close-modal');
const modalElement = document.querySelector('.modal');
// let myLibrary = [
// new Book('Down and Out in Paris and London', 'George Orwell', 232, true),
// new Book('Homage to Catalonia', 'George Orwell', 202, true),
// new Book('Shooting an Elephant', 'George Orwell', 368, false),
// ];
// let count = myLibrary.length - 3;
let myLibrary = [];
let count = myLibrary.length;
// Constructor...
function Book(title, author, pages, read) {
this.title = title;
this.author = author;
this.pages = Number(pages);
this.read = Boolean(read);
// Methods
this.bookInfo = function() {
const wasRead = this.read === true ? 'read' : 'not read';
return `${this.title} written by ${this.author}, ${this.pages} pages in length was ${wasRead}.`;
};
return this.bookInfo();
}
function createBook(e) {
e.preventDefault();
// myLibrary = [];
let title = document.querySelector('#title').value;
let author = document.querySelector('#author').value;
let pages = document.querySelector('#pages').value;
let read = document.querySelector('#read').value;
// Instantiate new Book object
const newBook = new Book(title, author, pages, read); // Add ID when instantiating
addBookToLibrary(newBook);
clearForm();
viewBookList(myLibrary);
}
function addBookToLibrary(book) {
// Hide modal
removeClass();
// Add book to array
return myLibrary.push(book);
}
function clearForm() {
document.querySelector('#form').reset();
}
function setCardStyle(element, details) {
element.setAttribute(
'style',
'display: flex; flex-direction: column; justify-content: space-between; text-align: center; background-color: #fff; padding: 1em; margin: 1em 1em 1em 0; border-radius: 5px; height: 250px; width: 250px; line-height: 1.5; box-shadow: 0 5px 10px 2px rgba(0, 0, 0, 0.2);',
);
element.innerHTML = `
<h3 class="title">${details.title}</h3>
<br>
<hr>
<br>
<p>${details.author}</p>
<p>${details.pages} pages</p>
<p>${details.read === true ? 'Read' : 'Unread'}</p>`;
}
function createCard() {
let bookCard = document.createElement('div');
bookCard.classList.add('card');
bookCard.setAttribute('data-target', `${count++}`); // Set target ID
return bookCard;
}
function removeBookBtn() {
let btn = document.createElement('button');
// Style button
btn.setAttribute(
'style',
'color: red; height: 2.5em; width: 50%; border-radius: 5px; margin: 0 auto; font-weight: bold; text-transform: uppercase; cursor: pointer;',
);
btn.innerHTML = 'Delete';
return btn;
}
function handleDelete(e) {
// Get book's data-target
let bookIndex = parseInt(e.path[1].attributes[1].value);
// console.log(bookIndex);
myLibrary.splice(bookIndex, 1);
// console.log(newArray);
// myLibrary = myLibrary.filter((book, index) => index !== bookIndex);
return viewBookList(myLibrary);
}
function viewBookList(list) {
const bookDiv = document.querySelector('.book-list');
bookDiv.innerHTML = "";
console.log(myLibrary);
for (book in list) {
let bookDetails = list[book];
let renderCard = createCard();
const deleteButton = removeBookBtn();
deleteButton.addEventListener('click', handleDelete);
setCardStyle(renderCard, bookDetails);
renderCard.appendChild(deleteButton);
bookDiv.appendChild(renderCard);
}
return bookDiv;
}
function addClass() {
return modalElement.classList.add('open');
}
function removeClass() {
return modalElement.classList.remove('open');
}
// Event listeners
btnOpenModal.addEventListener('click', addClass);
btnCloseModal.addEventListener('click', removeClass);
submitButton.addEventListener('click', createBook);
#import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap');
:root {
--roboto: 'Roboto', sans-serif;
--pt: "PT Sans", sans-serif;
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
html {
font-family: var(--roboto);
}
body {
min-height: 100vh;
display: flex;
justify-content: center;
background-image: linear-gradient(to top, #a6c1ee 0%, #fbc2eb 100%);
}
.header {
text-align: center;
}
.header h1 {
color: #fff;
font-size: 4rem;
text-shadow: 1px 2px 5px #000;
}
.modal {
padding: 1em;
background-color: #fff;
}
.label {
text-transform: capitalize;
}
.btn {
font-family: "PT Sans", sans-serif;
font-size: 1.2rem;
padding: 1rem 2.5rem;
cursor: pointer;
border: none;
}
.modal {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
align-items: center;
justify-content: center;
background: rgba(0, 0, 0, 0.7);
}
.open-modal {
background: #fff;
border-radius: 5px;
box-shadow: 0 5px 10px 2px rgba(0, 0, 0, 0.2);
transition: all 0.2s linear;
}
.open-modal:hover {
box-shadow: none;
background: rgba(255, 255, 255, 0.8);
}
.modal.open {
display: flex;
}
.form {
padding: 5em;
}
.modal-container {
background-color: #fff;
width: 90%;
max-width: 450px;
position: relative;
}
.modal.open .modal-container {
animation: move 0.6s ease-out;
}
#keyframes move {
from {
transform: translateY(-50px);
}
to {
transform: translateY(0px);
}
}
.close-modal {
font-size: 3rem;
position: absolute;
top: 0;
right: 0;
background-color: #fff;
height: 40px;
width: 40px;
text-align: center;
line-height: 40px;
cursor: pointer;
transition: color 0.15s linear;
}
.close-modal:hover {
color: #f00;
}
.book-list {
display: flex;
flex-wrap: wrap;
margin-top: 1.5em;
gap: 2em;
}
/* Created in app.js */
/* .card {
} */
<!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">
<link rel="stylesheet" href="styles/style.css">
<script src="scripts/app.js" defer></script>
<title>Odin Library</title>
</head>
<body>
<div class="container">
<header class="header">
<h1>Library</h1>
</header>
<section class="modal open">
<div class="modal-container">
<span id="close-modal" class="close-modal">×</span>
<form action="" method="POST" name="bookForm" id="form" class="form">
<div class="form-row">
<label for="title" class="label">title: </label>
<input type="text" name="title" id="title" placeholder="Animal Farm" required>
</div>
<div class="form-row">
<label for="author" class="label">author: </label>
<input type="text" name="author" id="author" placeholder="George Orwell" required>
</div>
<div class="form-row">
<label for="pages" class="label">pages: </label>
<input type="number" name="pages" id="pages" placeholder="232" required>
</div>
<div class="form-row">
<label for="read" class="label">read: </label>
<input type="checkbox" name="read" id="read" required>
</div>
<div class="button-container">
<input type="submit" value="Create" id="submit" class="submit">
</div>
</form>
</div>
</section class="card-section">
<section>
<!-- Add plus icon -->
<button class="btn open-modal" id="open-modal">Add Book</button>
<div class="book-list">
<!-- Container for cards -->
</div>
</section>
</div>
</body>
</html>
I am building a quiz app for practice in Javascript and have created all the questions.. I have made it go to the next question when the "Next Question button" is clicked, and have the correct answer console logging, but can't find out how to implement it to see if it matches the users input. If I can track it, I will add it to a "currentScore counter"
CODE:
let question = document.querySelector('.question')
let answerbox = document.querySelector('.answer-container')
let quizbox = document.querySelector('.quiz-container')
let answer1 = document.getElementById('a1')
let answer2 = document.getElementById('a2')
let answer3 = document.getElementById('a3')
let answer4 = document.getElementById('a4')
let answers = document.getElementsByClassName('answer')
let submitBtn = document.getElementById('submit-btn')
let currentquestion = 0
let currentscore = 0
const questionsData = [{
question: "How old am I?",
answers: {
a: "18",
b: "21",
c: "25",
d: "35",
},
correctAnswer: "b"
},
{
question: "What is my favorite color?",
answers: {
a: "Purple",
b: "Green",
c: "Black",
d: "Red",
},
correctAnswer: "c"
},
{
question: "What is my middle name?",
answers: {
a: "Albert",
b: "David",
c: "Graham",
d: "John",
},
correctAnswer: "d"
},
]
const loadquestion = () => {
console.log('working!!!')
//GETTING THE CORRECT ANSWER //
let correctAnswer = (questionsData[currentquestion].correctAnswer)
console.log(correctAnswer)
//RESET CLICK WHEN CLICKED OUTSIDE
const clickreset = (e) => {
if (e.target !== quizbox) {
// console.log(answer1.checked)
answer1.checked = false
answer2.checked = false
answer3.checked = false
answer4.checked = false
} else {
}
}
window.addEventListener('click', clickreset)
// console.log(questionsData[currentquestion].answers)
//INPUTTING THE QUESTIONS AND ANSWERS FROM THE QUIZDATE
question.innerText = questionsData[currentquestion].question
answer1.innerText = questionsData[currentquestion].answers.a
answer2.innerText = questionsData[currentquestion].answers.b
answer3.innerText = questionsData[currentquestion].answers.c
answer4.innerText = questionsData[currentquestion].answers.d
for (i = 0; i < answers.length; i++) {
let answerels = answers[i];
//RESETTING THE SELECTED ANSWER WHEN THE USER MOVES ON TO THE NEXT QUESTION
answerels.checked = false
}
currentquestion++
}
loadquestion()
const endofquiz = () => {
//GIVING RESULTS AT THE END
question.innerText = 'You answered ___ out of ___'
answer1.style.opacity = '0'
answer2.style.opacity = '0'
answer3.style.opacity = '0'
answer4.style.opacity = '0'
submitBtn.innerText = 'Restart Quiz'
submitBtn.addEventListener('click', () => {
location.reload()
})
}
submitBtn.addEventListener('click', () => {
//KEEP TRACK OF QUESTIONS UNTIL QUIZ IS FINISHED
if (currentquestion < questionsData.length) {
for (i = 0; i < answers.length; i++) {
let answerels = answers[i];
//CHECK TO SEE IF USER HAS SELECTED AN ANSWER
if (answerels.checked == true) {
//CHECK TO SEE IF USER HAS SELECTED AN ANSWER
//MOVE ON TO NEXT QUESTION
loadquestion()
// console.log('checked!')
} else {
//STOP USER FROM GOING TO NEXT QUESTION WITHOUT SELECTING AN ANSWER
// console.log('not checked! :(')
}
}
} else {
// SHOW RESULTS
endofquiz()
}
})
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
::-webkit-scrollbar {
display: none;
}
.wrapper {
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-around;
}
.quiz-container {
margin-top: 3em;
height: 75vh;
width: 50vw;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-evenly;
box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px;
}
.question-container {
height: 25vh;
width: 80vh;
/* position: absolute; */
/* top: 10%;
left: 50%; */
/* transform: translate(-50%, -10%); */
background-color: rgb(59, 0, 223);
box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px;
}
.question {
padding: 1em 1.5em;
font-size: 1.8rem;
text-align: center;
color: white;
}
.answer-container {
height: 25vh;
width: 50vh;
display: flex;
margin-top: -5em;
flex-direction: column;
}
label {
background-color: white;
padding: 0.5em;
margin: 0.5em;
position: relative;
text-align: center;
font-weight: bold;
font-size: 1.2rem;
cursor: pointer;
border: 2px solid rgb(59, 0, 223);
}
label:hover {
background-color: rgb(59, 0, 223);
color: white;
cursor: pointer;
transition: 0.45s ease;
}
input[type="radio"] {
opacity: 0;
}
input:checked+label {
background-color: rgb(59, 0, 223);
color: white;
cursor: pointer;
transition: 0.45s ease;
}
.submit-btn {
margin-top: 3em;
background-color: white;
outline: none;
border: 2px solid rgb(59, 0, 223);
padding: 0.5em 1.5em;
font-weight: bold;
font-size: 1.3rem;
width: 10%;
}
.submit-btn:hover {
color: white;
background-color: rgb(59, 0, 223);
transition: 0.45s ease;
cursor: pointer;
}
<!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>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="wrapper">
<div class="quiz-container" id="quiz-container">
<div class="question-container">
<h1 class="question">Lorem ipsum, dolor sit amet consectetur adipisicing elit. Eveniet, inventore.</h1>
</div>
<div class="answer-container">
<input class="answer" id='an1' type="radio" name="a"></input> <label id="a1" for="an1">lorem</label>
<input class="answer" id='an2' type="radio" name="a"></input> <label id="a2" for="an2">lorem</label>
<input class="answer" id='an3' type="radio" name="a"></input> <label id="a3" for="an3">lorem</label>
<input class="answer" id='an4' type="radio" name="a"></input> <label id="a4" for="an4">lorem</label>
</div>
</div>
<button class="submit-btn" id="submit-btn">Next Question</button>
</div>
<script src="app.js"></script>
</body>
</html>
Give each answer button a value that corresponds to the answer keys in the questionsData array. Then you can check if the selected button matches correctAnswer.
Also make correctAnswer a global variable so you can use it in the submit button listener.
I needed to make some changes to the logic of when it calls loadquestion() or endofquiz(), so that it checks the result of the last question and still calls endofquiz() at the end.
let question = document.querySelector('.question')
let answerbox = document.querySelector('.answer-container')
let quizbox = document.querySelector('.quiz-container')
let answer1 = document.getElementById('a1')
let answer2 = document.getElementById('a2')
let answer3 = document.getElementById('a3')
let answer4 = document.getElementById('a4')
let answers = document.getElementsByClassName('answer')
let submitBtn = document.getElementById('submit-btn')
let currentquestion = 0
let currentscore = 0
let correctAnswer = ''
const questionsData = [{
question: "How old am I?",
answers: {
a: "18",
b: "21",
c: "25",
d: "35",
},
correctAnswer: "b"
},
{
question: "What is my favorite color?",
answers: {
a: "Purple",
b: "Green",
c: "Black",
d: "Red",
},
correctAnswer: "c"
},
{
question: "What is my middle name?",
answers: {
a: "Albert",
b: "David",
c: "Graham",
d: "John",
},
correctAnswer: "d"
},
]
const loadquestion = () => {
//console.log('working!!!')
//GETTING THE CORRECT ANSWER //
correctAnswer = (questionsData[currentquestion].correctAnswer)
//console.log(correctAnswer)
//RESET CLICK WHEN CLICKED OUTSIDE
const clickreset = (e) => {
if (e.target !== quizbox) {
// console.log(answer1.checked)
answer1.checked = false
answer2.checked = false
answer3.checked = false
answer4.checked = false
} else {}
}
window.addEventListener('click', clickreset)
// console.log(questionsData[currentquestion].answers)
//INPUTTING THE QUESTIONS AND ANSWERS FROM THE QUIZDATE
question.innerText = questionsData[currentquestion].question
answer1.innerText = questionsData[currentquestion].answers.a
answer2.innerText = questionsData[currentquestion].answers.b
answer3.innerText = questionsData[currentquestion].answers.c
answer4.innerText = questionsData[currentquestion].answers.d
for (i = 0; i < answers.length; i++) {
let answerels = answers[i];
//RESETTING THE SELECTED ANSWER WHEN THE USER MOVES ON TO THE NEXT QUESTION
answerels.checked = false
}
currentquestion++
}
loadquestion()
const endofquiz = () => {
//GIVING RESULTS AT THE END
question.innerText = `You answered ${currentscore} out of ${questionsData.length}`
answer1.style.opacity = '0'
answer2.style.opacity = '0'
answer3.style.opacity = '0'
answer4.style.opacity = '0'
submitBtn.innerText = 'Restart Quiz'
submitBtn.addEventListener('click', () => {
location.reload()
})
}
submitBtn.addEventListener('click', () => {
//KEEP TRACK OF QUESTIONS UNTIL QUIZ IS FINISHED
if (currentquestion <= questionsData.length) {
for (i = 0; i < answers.length; i++) {
let answerels = answers[i];
//CHECK TO SEE IF USER HAS SELECTED AN ANSWER
if (answerels.checked == true) {
//CHECK TO SEE IF USER HAS SELECTED AN ANSWER
//MOVE ON TO NEXT QUESTION
if (answerels.value == correctAnswer) {
console.log("That's correct!");
currentscore++;
} else {
console.log(`Sorry, the correct answer is ${questionsData[currentquestion-1].answers[correctAnswer]}.`);
}
if (currentquestion < questionsData.length) {
loadquestion();
} else {
endofquiz();
}
} else {
//STOP USER FROM GOING TO NEXT QUESTION WITHOUT SELECTING AN ANSWER
// console.log('not checked! :(')
}
}
}
})
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
::-webkit-scrollbar {
display: none;
}
.wrapper {
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-around;
}
.quiz-container {
margin-top: 3em;
height: 75vh;
width: 50vw;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-evenly;
box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px;
}
.question-container {
height: 25vh;
width: 80vh;
/* position: absolute; */
/* top: 10%;
left: 50%; */
/* transform: translate(-50%, -10%); */
background-color: rgb(59, 0, 223);
box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px;
}
.question {
padding: 1em 1.5em;
font-size: 1.8rem;
text-align: center;
color: white;
}
.answer-container {
height: 25vh;
width: 50vh;
display: flex;
margin-top: -5em;
flex-direction: column;
}
label {
background-color: white;
padding: 0.5em;
margin: 0.5em;
position: relative;
text-align: center;
font-weight: bold;
font-size: 1.2rem;
cursor: pointer;
border: 2px solid rgb(59, 0, 223);
}
label:hover {
background-color: rgb(59, 0, 223);
color: white;
cursor: pointer;
transition: 0.45s ease;
}
input[type="radio"] {
opacity: 0;
}
input:checked+label {
background-color: rgb(59, 0, 223);
color: white;
cursor: pointer;
transition: 0.45s ease;
}
.submit-btn {
margin-top: 3em;
background-color: white;
outline: none;
border: 2px solid rgb(59, 0, 223);
padding: 0.5em 1.5em;
font-weight: bold;
font-size: 1.3rem;
width: 10%;
}
.submit-btn:hover {
color: white;
background-color: rgb(59, 0, 223);
transition: 0.45s ease;
cursor: pointer;
}
<!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>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="wrapper">
<div class="quiz-container" id="quiz-container">
<div class="question-container">
<h1 class="question">Lorem ipsum, dolor sit amet consectetur adipisicing elit. Eveniet, inventore.</h1>
</div>
<div class="answer-container">
<input class="answer" id='an1' type="radio" name="a" value="1"></input> <label id="a1" for="an1">lorem</label>
<input class="answer" id='an2' type="radio" name="a" value="b"></input> <label id="a2" for="an2">lorem</label>
<input class="answer" id='an3' type="radio" name="a" value="c"></input> <label id="a3" for="an3">lorem</label>
<input class="answer" id='an4' type="radio" name="a" value="d"></input> <label id="a4" for="an4">lorem</label>
</div>
</div>
<button class="submit-btn" id="submit-btn">Next Question</button>
</div>
<script src="app.js"></script>
</body>
</html>
I am currently making a chrome extension (This is my first chrome extension) that you can take small notes with and want to keep the user input. I am keeping the user input inside of input classes. How would I be able to store the chrome extension state so that when I reopen it, it will stay the same? Here is the code that I have written so far.
//selectors
const addbutton = document.querySelector(".add");
const addlist = document.querySelector(".note-list");
const noteList = document.querySelector(".note-list")
//event listners
addbutton.addEventListener('click', addNote);
//functions
function addNote(event){
//prevent page refresh
event.preventDefault();
//note div
const noteDiv = document.createElement('div');
noteDiv.classList.add('note');
//create li
const newNote = document.createElement('li');
newNote.classList.add('noteitem');
noteDiv.appendChild(newNote);
//create input
const newInput = document.createElement('input');
newInput.classList.add('noteInput')
newNote.appendChild(newInput);
//append to list
noteList.appendChild(noteDiv);
}
#import url('https://fonts.googleapis.com/css2?family=Montserrat:wght#500&display=swap');
*{
margin: 0;
padding: 0;
box-sizing: border-box;
outline: none;
}
body{
height: 500px;
width: 400px;
}
h1{
font-family: "Montserrat", sans-serif;
font-size: 20px;
font-weight: lighter;
padding-top: 10px;
padding-bottom: 10px;
}
main{
text-align: center;
}
.title{
box-shadow: 0 2px 2px -2px rgba(0, 0, 0, 0.685);
}
.mainpage{
padding-top: 20px;
}
.add{
font-family: "Montserrat", sans-serif;
font-size: 25px;
font-weight: 400px;
background-color: #00FF33;
width:40px ;
height: 40px;
border-radius: 10px;
border: none;
transition: ease 0.5s;
}
.add:hover{
background-color: #00c026;
}
.note-container{
display: flex;
justify-content: center;
align-items: center;
}
.note-list{
min-width: 30%;
list-style: none;
}
.note{
margin: 0.5rem;
background: whitesmoke;
font-size: 1.5rem;
display: flex;
justify-content: space-between;
border-radius: 7px;
}
.noteitem{
padding: 0.5rem 2rem;
}
.noteInput{
display: block;
margin-right: auto;
margin-left: auto;
border: none;
background-color: whitesmoke;
font-size: 20px;
max-height: 200px;
}
.note li{
flex: 1;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mini Note</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<main>
<div class="title">
<h1>Mini note app</h1>
</div>
<section class="mainpage">
<button class="add">+</button>
<div class="note-container">
<ul class="note-list"></ul>
</div>
</section>
</main>
<script src="/popup.js"></script>
</body>
</html>
Thank you
// uses local storage
chrome.storage.local.set({key: value}, function() {
console.log('Value is set to ' + value);
});
// uses synced storage, hits Chrome backend when being set
chrome.storage.sync.set({key: value}, function() {
console.log('Value is set to ' + value);
});
// to retrieve the data, use 'sync' instead of 'local' if using sync
chrome.storage.local.get(['key'], function(result) {
console.log('Value currently is ' + result.key);
});
You'll still need to figure out how you want to organize the note data. For example, you could store all of the notes in an array on the notes key that looks like the following:
{
notes: [
{ id: 1, body: 'First note' },
{ id: 2, body: 'Second note' }
]
}
you have two options :-
you can use localStorage just like in web page for more check here
you can use chrome.storage for more check here
So I'm making a calculator in JavaScript as a way to learn JavaScript. I'd like to add some sort of Object Orientated into the project.
My 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>The Unconventional Calculator</title>
<link
href="https://fonts.googleapis.com/css?family=Roboto:400,700&display=swap"
rel="stylesheet"
/>
<link rel="stylesheet" href="assets/styles/app.css" />
</head>
<body>
<header>
<h1>The Unconventional Calculator</h1>
</header>
<section id="calculator">
<input type="number" id="input-number" />
<div id="calc-actions">
<button type="button" id="btn-add">+</button>
<button type="button" id="btn-subtract">-</button>
<button type="button" id="btn-multiply">*</button>
<button type="button" id="btn-divide">/</button>
<button type="button" id="btn-equals">=</button>
</div>
</section>
<section id="results">
<h2 id="current-calculation">0</h2>
<h2>Result: <span id="current-result">0</span></h2>
</section>
<section class="credit">
<h1>Check out my code on GitHub
<br>Type your number, press enter, repeat until you're done and then press enter.</h1>
</section>
<!-- So the site loads first then the js runs -->
<script src="assets/scripts/vendor.js"></script>
<script src="assets/scripts/app.js"> </script>
</body>
</html>
MY CSS
* {
box-sizing: border-box;
}
html {
font-family: 'Roboto', open-sans;
}
body {
margin: 0;
}
header {
background: #6d0026;
color: white;
padding: 1rem;
text-align: center;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.26);
width: 100%;
}
#results,
#calculator {
margin: 2rem auto;
width: 40rem;
max-width: 90%;
border: 1px solid #6d0026;
border-radius: 10px;
padding: 1rem;
color: #6d0026;
}
#results {
text-align: center;
}
#calculator input {
font: inherit;
font-size: 3rem;
border: 2px solid #6d0026;
width: 10rem;
padding: 0.15rem;
margin: auto;
display: block;
color: #6d0026;
text-align: center;
}
#calculator input:focus {
outline: none;
}
#calculator button {
font: inherit;
background: #6d0026;
color: white;
border: 1px solid #6d0026;
padding: 1rem;
cursor: pointer;
}
#calculator button:focus {
outline: none;
}
#calculator button:hover,
#calculator button:active {
background: #6d2d1b;
border-color: #6d2d1b;
}
#calc-actions button {
width: 4rem;
}
#calc-actions {
margin-top: 1rem;
text-align: center;
}
.credit {
margin: 70px 0 0 0;
text-align: center;
}
app.js
// Base Variables
let result = 0;
let number = 0;
//Store equation as string
let calculationDescription = "";
//Event listeners
document.querySelector("#btn-add").addEventListener('click', sumNumbs);
document.querySelector("#btn-subtract").addEventListener('click', subtractNumbs);
document.querySelector("#btn-multiply").addEventListener('click', multiplyNumbs);
document.querySelector("#btn-divide").addEventListener('click', divideNumbs);
document.querySelector("#btn-equals").addEventListener('click', equals);
document.querySelector('#input-number').addEventListener('keypress', numbersInput);
function numbersInput(e) {
if(e.key === 'Enter' && userInput !== null) {
number = e.target.value;
e.target.value = '';
calculationDescription += number + " ";
console.log(calculationDescription);
}
}
function sumNumbs() {
calculationDescription += "+ ";
}
function subtractNumbs() {
calculationDescription += "- ";
}
function multiplyNumbs() {
calculationDescription += "x ";
}
function divideNumbs() {
calculationDescription += "/ ";
}
function equals() {
let finalCalculation = calculationDescription.split(" ");
//Goes to errorHandler to remove whitespace and make array ready for equation
errorHandler.removeWhiteSpace(finalCalculation);
}
errorHandler.js
class errorHandler {
static removeWhiteSpace(arraySplit) {
return console.log(arraySplit);
}
}
vendor.js(this one isn't to important for the solution)
const userInput = document.getElementById('input-number');
const addBtn = document.getElementById('btn-add');
const subtractBtn = document.getElementById('btn-subtract');
const multiplyBtn = document.getElementById('btn-multiply');
const divideBtn = document.getElementById('btn-divide');
const equalsBtn = document.getElementById('btn-equals');
const currentResultOutput = document.getElementById('current-result');
const currentCalculationOutput = document.getElementById('current-calculation');
function outputResult(result, text) {
currentResultOutput.textContent = result;
currentCalculationOutput.textContent = text;
}
So in my equals method I'd like to send the array finalCalculation which is in the app.js class into the removeWhiteSpace method that's in my errorHandler.js
This is the error I keep getting
app.js:44 Uncaught ReferenceError: errorHandler is not defined
at HTMLButtonElement.equals (app.js:44)
I've tried turning both of them into classes and then creating a constructor with an instance variable for errorHandler to take in the array, but that doesn't seem to work.
I am creating a game of Boggle using an external javascript page to create the arrays. The problem I am having is
Chrome doesn't display the letters without creating a button to display them separately.
As the user enters words, the words are not displaying until the user quits the game.
It works fine on Firefox but I want it to work in Chrome too.
Any suggestions?
function words(x) {
switch (x) {
case 1:
var word = new Array("balte", "table", "hat", "tab", "belt", "lab", "eat", "tea", "ate", "tale", "bale", "let", "bet", "teal", "late", "beat");
break;
case 2:
var word = new Array("atwre", "water", "wet", "wear", "tear", "war", "ret", "rate", "eat", "ate", "tea", "awe", "raw", "rat", "wart", "art", "tar");
break;
case 3:
var word = new Array("dclaen", "can", "cane", "and", "clan", "lane", "lean", "lend", "land", "den", "dean", "dance", "lance", "clean", "deal", "ale", "dale", "candle", "clad");
break;
case 4:
var word = new Array("aepinlar", "air", "airplane", "plane", "plan", "lane", "lean", "pane", "ear", "near", "nap", "nape", "lair", "pen", "pan", "ape", "leap", "ale", "peal", "nap", "rap", "par", "pare", "pale", "are", "rail", "ail", "pail", "nail", "air", "pair", "ran", "pin", "pine", "line", "nip", "rip", "ripe", "lip", "earn", "learn", "ire");
break;
case 5:
var word = new Array("redykboa", "keyboard", "key", "board", "bored", "bore", "bark", "dark", "dork", "oar", "boar", "ark", "dare", "bare", "are", "red", "rod", "road", "bode", "rode", "ode", "bread", "read", "bead", "bred", "break", "drey", "day", "boy", "broke", "rake", "bake", "ear", "dear", "bear", "dye", "dyer", "doer", "oak", "boa", "doe", "okay", "dab", "bade", "ade", "drake", "bard", "yard", "year", "beak", "beard", "bad", "bed", "bay");
break;
}
return word;
}
compWords = new Array();
notAword = new Array();
playWords = new Array();
function displayLetters() {
var num = Math.floor(Math.random() * 5) + 1;
compWords = words(num);
yourWord = compWords[0];
document.getElementById("letters").innerHTML = yourWord;
}
function displayEntries() {
document.getElementById("entries").innerHTML = playWords.toString();
}
function boggle() {
var play = "";
var score = 0;
var flag = 0;
//get player entries
while (play != "Q") {
play = prompt("enter a word or enter Q when done");
playWords.push(play);
if (play != "Q")
//document.getElementById("entries").innerHTML = playWords.toString();
displayEntries();
}
// check winning score and list bad words
var complgth = compWords.length;
var playlgth = (playWords.length - 1);
for (var i = 0; i < playlgth; i++) {
flag = 0;
for (var k = 0; k < complgth; k++) {
if (playWords[i] == compWords[k]) {
score++;
flag = 1;
}
}
if (flag == 0)
notAword.push(playWords[i]);
}
document.getElementById("result").innerHTML = ("Your score is " +
score + ". The following entries " +
"are not valid words: <br />" +
notAword.toString());
}
body {
background-color: #000040;
color: #88ffff;
font-family: Verdana, Arial, sans-serif;
}
#container {
margin-left: auto;
margin-right: auto;
width: 80%;
min-width: 700px;
}
#logo {
text-align: center;
margin: 0;
font-family: Geneva, Arial, Helvetica, sans-serif;
padding-top: 30px;
padding-bottom: 20px;
}
#nav {
float: left;
width: 200px;
padding-top: 10px;
text-align: left;
color: #88FFFF;
font-size: 12px;
}
#nav a {
text-decoration: none;
margin: 15px;
display: block;
color: #88FFFF;
font-size: 12px;
}
#content {
margin-left: 150px;
padding: 30px;
overflow: auto;
border: medium groove #88FFFF;
line-height: 135%;
}
.floatright {
padding-left: 20px;
float: right;
}
.floatleft {
float: left;
padding: 30px 0px 20px;
}
#footer {
font-size: .60em;
font-style: italic;
text-align: center;
border-top: 2px double #000040;
padding-top: 20px;
padding-bottom: 20px;
}
h2 {
text-transform: uppercase;
color: #88ffff;
font-size: 1.2em;
border-bottom: 1px none;
margin-right: 20px;
}
h3 {
color: #88ffff;
font-size: 1.2em;
border-bottom: 1px solid #000000;
margin-right: auto;
text-align: left;
padding-top: 10px;
padding-right: 20px;
padding-bottom: 10px;
padding-left: 20px;
line-height: 120%;
}
.details {
padding-left: 20%;
padding-right: 20%;
}
img {
border: 0;
}
.content {
margin: 20px;
padding: 20px;
height: 3700px;
width: 500px;
}
a {
text-decoration: none;
margin: 15px;
display: block;
color: #88FFFF;
font-size: 12px;
}
a:hover {
color: #000040;
background-color: #88ffff;
}
span {
font-size: 20px;
font-weight: bold;
font-family: "Courier New", Courier, mono;
color: #88ffff;
background-position: center center;
text-align: center;
vertical-align: middle;
}
table {
border-collapse: collapse
}
td {
border: 2px solid #88ffff;
width: 5em;
color: #88ffff;
}
.nobdr {
border: none;
cell-padding: 5px;
}
.OK {
border-radius: 50%;
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Greg's Gambits | Greg's Game of Boggle</title>
<link href="greg.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="gregBoggle.js"></script>
<script>
</script>
</head>
<body>
<div id="container">
<img src="images/superhero.jpg" width="120" height="120" class="floatleft" />
<h1 align="center"><em>Greg's Game of Boggle</em></h1>
<div style="clear:both;"></div>
<div id="nav">
<p>Home
About
Play a Game
Sign In
Contact Us</p>
</div>
<div id="content">
<p>The object of the game is to create as many words as you can, in a given time limit, from the letters show below. When you are ready to begin, click the Diplay letters button, then Begin game button.</p>
<p><input type="button" value="Display letters" onclick="displayLetters();" /></p>
<p><input type="button" value="Begin the game" onclick="boggle();" /></p>
<h2><br /><br />Letters you can use:<br />
<div id="letters"> </div><br /></h2>
<h2>Your words so far: <br />
<div id="entries"> </div><br /></h2>
<h2>Results:<br />
<div id="result"> </div>
</h2>
</div>
<div id="footer">Copyright © 2013 Greg's Gambits<br />
foulksy#gmail.com
</div>
</div>
</body>
</html>
Browsers aren't required to render DOM changes until the script finishes and returns to the main event loop. Firefox also does this when you call prompt(), but I don't think this is required.
Instead of using a while loop, you should use an input element that the user fills in. You can then use an event listener to read the input and update the DOM. This will work in all browsers.