How to add an image to JavaScript Quiz - javascript

I am creating a quiz in Javascript but I want to replace my questions with images instead. i.e the logos of the programming languages. I have seen other examples but none to what I need. If anyone could help I would really appreciate it.
Sorry that snippet is not working, not use to it. I hope the code below helps expalin what I am asking
function populate() {
if (quiz.isEnded()) {
showScores();
} else {
// show question
var element = document.getElementById("question");
element.innerHTML = quiz.getQuestionIndex().text;
// show options
var choices = quiz.getQuestionIndex().choices;
for (var i = 0; i < choices.length; i++) {
var element = document.getElementById("choice" + i);
element.innerHTML = choices[i];
guess("btn" + i, choices[i]);
}
showProgress();
}
};
function guess(id, guess) {
var button = document.getElementById(id);
button.onclick = function() {
quiz.guess(guess);
//populate();
}
};
function showProgress() {
var currentQuestionNumber = quiz.questionIndex + 1;
var element = document.getElementById("progress");
element.innerHTML = "Question " + currentQuestionNumber + " of " + quiz.questions.length;
};
function showScores() {
var gameOverHTML = "<h1>Result</h1>";
gameOverHTML += "<h2 id='score'> Your scores: " + quiz.score + "</h2>";
var element = document.getElementById("quiz");
element.innerHTML = gameOverHTML;
};
// create questions
var questions = [
new Question("Which one is not an object oriented programming language?", ["Java", "C#", "C++", "C"], "C"),
new Question("Which language is used for styling web pages?", ["HTML", "JQuery", "CSS", "XML"], "CSS"),
new Question("There are ____ main components of object oriented programming.", ["1", "6", "2", "4"], "4"),
new Question("Which language is used for web apps?", ["PHP", "Python", "Javascript", "All"], "All"),
new Question("MVC is a ____.", ["Language", "Library", "Framework", "All"], "Framework")
];
function Question(text, choices, answer) {
this.text = text;
this.choices = choices;
this.answer = answer;
}
Question.prototype.isCorrectAnswer = function(choice) {
return this.answer === choice;
}
function Quiz(questions) {
this.score = 0;
this.questions = questions;
this.questionIndex = 0;
}
Quiz.prototype.getQuestionIndex = function() {
return this.questions[this.questionIndex];
}
Quiz.prototype.guess = function(answer) {
if (this.getQuestionIndex().isCorrectAnswer(answer)) {
this.score++;
}
this.questionIndex++;
}
Quiz.prototype.isEnded = function() {
return this.questionIndex === this.questions.length;
}
// create quiz
var quiz = new Quiz(questions);
// display quiz
populate();
body {
background-color: #eeeeee;
}
.grid {
width: 600px;
height: 500px;
margin: 0 auto;
background-color: #fff;
padding: 10px 50px 50px 50px;
border-radius: 50px;
border: 2px solid #cbcbcb;
box-shadow: 10px 15px 5px #cbcbcb;
}
.grid h1 {
font-family: "sans-serif";
background-color: #57636e;
font-size: 60px;
text-align: center;
color: #ffffff;
padding: 2px 0px;
border-radius: 50px;
}
#score {
color: #5A6772;
text-align: center;
font-size: 30px;
}
.grid #question {
font-family: "monospace";
font-size: 30px;
color: #5A6772;
}
.buttons {
margin-top: 30px;
}
#btn0,
#btn1,
#btn2,
#btn3 {
background-color: #778897;
width: 250px;
font-size: 20px;
color: #fff;
border: 1px solid #1D3C6A;
border-radius: 50px;
margin: 10px 40px 10px 0px;
padding: 10px 10px;
}
#btn0:hover,
#btn1:hover,
#btn2:hover,
#btn3:hover {
cursor: pointer;
background-color: #57636e;
}
#btn0:focus,
#btn1:focus,
#btn2:focus,
#btn3:focus {
outline: 0;
}
#progress {
color: #2b2b2b;
font-size: 18px;
}
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Quiz</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="grid">
<div id="quiz">
<h1>Quiz</h1>
<hr style="margin-bottom: 20px">
<p id="question"></p>
<div class="buttons">
<button id="btn0"><span id="choice0"></span></button>
<button id="btn1"><span id="choice1"></span></button>
<button id="btn2"><span id="choice2"></span></button>
<button id="btn3"><span id="choice3"></span></button>
</div>
<hr style="margin-top: 50px">
<footer>
<p id="progress">Question x of y</p>
</footer>
</div>
</div>
</body>
</html>

As York said, you need to upload/put the images to your server or get them from other URLs.
Next, you'll need to save them (probably in questions). In this example I used imgURL inside each Question.
Then use this code to show the image:
var element = document.getElementById("question");
element.innerHTML = '<img src=' + quiz.getQuestionIndex().imgURL + '" />'

I assume you mean this - replace the placeholder images with your own. The encodeURI was just because # and ++ are uri elements:
var images = {
"CSS" : "https://via.placeholder.com/200x50?text=CSS",
"HTML" : "https://via.placeholder.com/200x50?text=HTML",
"Java" : "https://via.placeholder.com/200x50?text=JAVA",
"C#" : "https://via.placeholder.com/200x50?text=C"+encodeURIComponent("#"),
"C++" : "https://via.placeholder.com/200x50?text=C"+encodeURIComponent("++"),
"C" : "https://via.placeholder.com/200x50?text=C"
}
function populate() {
if (quiz.isEnded()) {
showScores();
} else {
// show question
var element = document.getElementById("question");
element.innerHTML = quiz.getQuestionIndex().text;
// show options
var choices = quiz.getQuestionIndex().choices;
for (var i = 0; i < choices.length; i++) {
var element = document.getElementById("choice" + i);
element.innerHTML = images[choices[i]]? '<img src="'+images[choices[i]]+'"/>':choices[i];
guess("btn" + i, choices[i]);
}
showProgress();
}
};
function guess(id, guess) {
var button = document.getElementById(id);
button.onclick = function() {
quiz.guess(guess);
populate();
}
};
function showProgress() {
var currentQuestionNumber = quiz.questionIndex + 1;
var element = document.getElementById("progress");
element.innerHTML = "Question " + currentQuestionNumber + " of " + quiz.questions.length;
};
function showScores() {
var gameOverHTML = "<h1>Result</h1>";
gameOverHTML += "<h2 id='score'> Your scores: " + quiz.score + "</h2>";
var element = document.getElementById("quiz");
element.innerHTML = gameOverHTML;
};
// create questions
var questions = [
new Question("<img src='https://via.placeholder.com/200x50?text=OOP' /><br/>Which one is not an object oriented programming language?", ["Java", "C#", "C++", "C"], "C"),
new Question("<img src='https://via.placeholder.com/200x50?text=Web+development' /><br/>Which language is used for styling web pages?", ["HTML", "JQuery", "CSS", "XML"], "CSS"),
new Question("There are ____ main components of object oriented programming.", ["1", "6", "2", "4"], "4"),
new Question("Which language is used for web apps?", ["PHP", "Python", "Javascript", "All"], "All"),
new Question("MVC is a ____.", ["Language", "Library", "Framework", "All"], "Framework")
];
function Question(text, choices, answer) {
this.text = text;
this.choices = choices;
this.answer = answer;
}
Question.prototype.isCorrectAnswer = function(choice) {
return this.answer === choice;
}
function Quiz(questions) {
this.score = 0;
this.questions = questions;
this.questionIndex = 0;
}
Quiz.prototype.getQuestionIndex = function() {
return this.questions[this.questionIndex];
}
Quiz.prototype.guess = function(answer) {
if (this.getQuestionIndex().isCorrectAnswer(answer)) {
this.score++;
}
this.questionIndex++;
}
Quiz.prototype.isEnded = function() {
return this.questionIndex === this.questions.length;
}
// create quiz
var quiz = new Quiz(questions);
// display quiz
populate();
body {
background-color: #eeeeee;
}
.grid {
width: 600px;
height: 500px;
margin: 0 auto;
background-color: #fff;
padding: 10px 50px 50px 50px;
border-radius: 50px;
border: 2px solid #cbcbcb;
box-shadow: 10px 15px 5px #cbcbcb;
}
.grid h1 {
font-family: "sans-serif";
background-color: #57636e;
font-size: 60px;
text-align: center;
color: #ffffff;
padding: 2px 0px;
border-radius: 50px;
}
#score {
color: #5A6772;
text-align: center;
font-size: 30px;
}
.grid #question {
font-family: "monospace";
font-size: 30px;
color: #5A6772;
}
.buttons {
margin-top: 30px;
}
#btn0,
#btn1,
#btn2,
#btn3 {
background-color: #778897;
width: 250px;
font-size: 20px;
color: #fff;
border: 1px solid #1D3C6A;
border-radius: 50px;
margin: 10px 40px 10px 0px;
padding: 10px 10px;
}
#btn0:hover,
#btn1:hover,
#btn2:hover,
#btn3:hover {
cursor: pointer;
background-color: #57636e;
}
#btn0:focus,
#btn1:focus,
#btn2:focus,
#btn3:focus {
outline: 0;
}
#progress {
color: #2b2b2b;
font-size: 18px;
}
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Quiz</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="grid">
<div id="quiz">
<h1>Quiz</h1>
<hr style="margin-bottom: 20px">
<p id="question"></p>
<div class="buttons">
<button id="btn0"><span id="choice0"></span></button>
<button id="btn1"><span id="choice1"></span></button>
<button id="btn2"><span id="choice2"></span></button>
<button id="btn3"><span id="choice3"></span></button>
</div>
<hr style="margin-top: 50px">
<footer>
<p id="progress">Question x of y</p>
</footer>
</div>
</div>
</body>
</html>

Related

how to play audio file on each question on javascript

var questions = [];
var images = {}
So, the inside of "questions" array have another array that can call "images" array the problem here is how to call the "audio array" i have made an array for the audio but it seems not working
var sounds ={}
I have also tried another method which is putting html element inside of the array of variables but still, it's not working
HTML css
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Picture Quiz</title>
<style>
body {
background-color: #eeeeee;
}
.grid {
width: 68%;
height: 520px;
margin: 0 auto;
background-color: #fff;
padding: 10px 50px 50px 50px;
border-radius: 50px;
border: 2px solid #cbcbcb;
box-shadow: 10px 15px 5px #cbcbcb;
}
.buttons img
{
width:200px;
}
.grid h1 {
font-family: "sans-serif";
background-color: #ffc107;
font-size: 35px;
text-align: center;
color: #ffffff;
padding: 2px 0px;
border-radius: 50px;
}
hr
{
margin-top: 50px;
color: red;
background-color: #ffc107;
height: 2px;
border: none;
}
#score {
color: #ffc107;
text-align: center;
font-size: 30px;
}
.grid #question {
font-family: "monospace";
font-size: 30px;
color: #ffc107;
}
.buttons {
margin-top: 30px;
}
#btn0,
#btn1,
#btn2,
#btn3 {
padding: 0px;
font-size: 20px;
color: #fff;
border: none;
margin: 10px 20px 10px 0px;
}
#btn0:hover,
#btn1:hover,
#btn2:hover,
#btn3:hover {
cursor: pointer;
background-color: #ffc107;
}
#btn0:focus,
#btn1:focus,
#btn2:focus,
#btn3:focus {
outline: 0;
}
#progress {
color: #2b2b2b;
font-size: 18px;
}
</style>
</head>
<body>
<div class="grid">
<div id="quiz">
<h1>Picture Quiz</h1>
<hr style="margin-bottom: 20px">
<p id="question"></p>
<p id="audio"></p>
<div class="buttons">
<button id="btn0"><span id="choice0"></span></button>
<button id="btn1"><span id="choice1"></span></button>
<button id="btn2"><span id="choice2"></span></button>
<button id="btn3"><span id="choice3"></span></button>
</div>
<hr style="margin-top: 50px">
<footer>
<p id="progress">Question x of y</p>
</footer>
</div>
</div>
</body>
</html>
Javascript
var images = {
"dog": "dog.jpg",
"cow": "cow.jpg",
"cat": "cat.jpg",
"goat": "goat.jpg",
"deer": "deer.jpg",
"hen": "hen.jpg",
"lion": "lion.jpg",
"parrot": "parrot.jpg",
"tiger": "tiger.jpg"
}
var sounds = {
"audio1" : "grizz.mp3",
"audio2" : "immortal.mp3",
"audio3" : "genshoshi.mp3",
"audio4" : "genshoshi.mp3",
"audio5" : "immortal.mp3"
}
function populate() {
if (quiz.isEnded()) {
showScores();
} else {
// show question
var element = document.getElementById("question");
element.innerHTML = quiz.getQuestionIndex().text;
// show audio
var audio = document.getElementById("audio");
audio.innerHTML = quiz.getQuestionIndex().audio;
// show options
var choices = quiz.getQuestionIndex().choices;
for (var i = 0; i < choices.length; i++) {
var element = document.getElementById("choice" + i);
element.innerHTML = images[choices[i]]? '<img src="'+images[choices[i]]+'"/>':choices[i];
guess("btn" + i, choices[i]);
}
showProgress();
}
};
function guess(id, guess) {
var button = document.getElementById(id);
button.onclick = function() {
quiz.guess(guess);
populate();
}
};
function showProgress() {
var currentQuestionNumber = quiz.questionIndex + 1;
var element = document.getElementById("progress");
element.innerHTML = "Question " + currentQuestionNumber + " of " + quiz.questions.length;
};
function showScores() {
var gameOverHTML = "<h1>Result</h1>";
gameOverHTML += "<h2 id='score'> Your scores: " + quiz.score + "</h2>";
var element = document.getElementById("quiz");
element.innerHTML = gameOverHTML;
};
// create questions
var questions = [
new Question(["Which one is dog?"],"audio1",["cow", "goat", "cat", "dog"], "dog"),
new Question(["select tiger below"],"audio2",["parrot", "deer", "tiger", "lion"], "tiger"),
new Question(["choose parrot pls?"],"audio3",["hen", "parrot", "goat", "dog"], "parrot"),
new Question(["Find cat below?"],"audio4",["parrot", "goat", "cat", "tiger"], "cat"),
new Question(["choose lion pls?"],"audio5",["lion", "goat", "tiger", "dog"], "lion")
];
questions.sort(function(){
return 0.5 - Math.random();
});
function Question(text, audio , choices, answer) {
this.text = text;
this.audio = audio;
this.choices = choices;
this.answer = answer;
}
Question.prototype.isCorrectAnswer = function(choice) {
return this.answer === choice;
}
function Quiz(questions) {
this.score = 0;
this.questions = questions;
this.questionIndex = 0;
}
Quiz.prototype.getQuestionIndex = function() {
return this.questions[this.questionIndex];
}
Quiz.prototype.guess = function(answer) {
if (this.getQuestionIndex().isCorrectAnswer(answer)) {
this.score++;
}
this.questionIndex++;
}
Quiz.prototype.isEnded = function() {
return this.questionIndex === this.questions.length;
}
// create quiz
var quiz = new Quiz(questions);
// display quiz
populate();
I'm trying to make text sound1 into an audio button that can be played as my quiz later
For audio, you have to make an html element and grab that element by using its id and audio will only play when the user triggers it like when clicked it will not be automatically played.
You can refer this site for more information.
And please don't copy paste whole code while asking question, paste whatever is required.

When i click the next or previous the thumbnail's are not changed

its an image slider when I click the next I needs to change the image in the thumbnails also but its not working. also not showing main picture when I click in the the first picture and the second is working but third also not working...
thumbnail's are not change through next and previous...
in slider images are change through next and previous but the thumbnails are not change with image...
Code.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<style>
.newsslider {
width: 100%;
height: 800px;
background-color:#766582;
}
.text {
text-align: center;
font-size: 40px;
color: white;
margin-bottom: -101px;
}
.btn1,
.btn2 {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
margin-top: -30px;
padding: 16px;
color: #52492f;
font-weight: bold;
font-size: 20px;
border-radius: 0 3px 3px 0;
user-select: none;
}
.btn2 {
position: absolute;
right: 0;
border-radius: 3px 0 0 3px;
}
.btn1:hover,
.btn2:hover {
background-color: rgba(0, 0, 0, 0.8);
color: white;
}
.onebtn {}
.twobtn {}
.thumbs {
display: flex;
padding-top: 6%;
align-items: center;
justify-content: center;
list-style: none;
}
.thumbs li {
width: 12%;
padding: 10px;
margin: 1%;
}
.thumbs li img {
width: 100%;
}
.img12:hover {
box-shadow: 0 0 2px 1px rgba(0, 140, 186, 0.5);
}
</style>
</head>
<body>
<div class="newsslider">
<p class="text" id="demo"><img id="demo1" src="img5.png" width=30%; height=400px;> </p>
<div class="onebtn">
<button id="btn1" class="btn1" type="button" class="prev" onclick="prev()">PREV</button>
</div>
<div class="twobtn">
<button id="btn2" class="btn2" type="button" class="next" onclick="next()">NEXT</button>
</div>
<p id="newsArr1" class="text" style="font-size:40px; font-weight:bolder; color: #521d2c;">Hi,</p>
<ul class="thumbs">
<li class="img12" onclick="thumbchange(1)"><img src="img5.png" width=500%;></li>
<li class="img12" onclick="thumbchange(2)"><img src="img2.png"></li>
<li class="img12" onclick="thumbchange(3)"><img src="img4.png"></li>
</ul>
</div>
<script>
var newsArr = ['<img src="img5.png"width = 30%; height=400px;>',
'<img src="img2.png"width = 30%; height=400px; >',
'<img src="img4.png" width = 30%; height=400px;>'];
var newsArr1 = ["Hi",
"This is Urraan",
"Urraan is a digital gateway"];
var i = 0;
var x = document.getElementById("demo");
var y = document.getElementById("newsArr1");
// var timeoutId;
function next() {
// if (timeoutId) {
// clearTimeout(timeoutId);
// }
i++;
if (i < newsArr.length) {
x.innerHTML = newsArr[i];
y.innerHTML = newsArr1[i];
} else {
i = 0;
x.innerHTML = newsArr[i];
y.innerHTML = newsArr1[i];
}
// timeoutId = setTimeout(next, 2000);
}
function prev() {
i--;
if (i >= 0) {
x.innerHTML = newsArr[i];
y.innerHTML = newsArr1[i];
} else {
i = newsArr.length - 1;
x.innerHTML = newsArr[i];
y.innerHTML = newsArr1[i];
}
}
function thumbchange(num) {
var thumb = 'img' + num + '.png';
document.getElementById("demo1").src = thumb;
}
</script>
</body>
</html>
you problem solved ... please try it.
var newsArr = ['<img src="https://www.w3schools.com/bootstrap4/la.jpg"width = 100%; height=400px;>',
'<img src="https://www.w3schools.com/bootstrap4/chicago.jpg"width = 100%; height=400px; >',
'<img src="https://www.w3schools.com/bootstrap4/ny.jpg" width = 100%; height=400px;>'];
var newsArr1 = ["Hi",
"This is Urraan",
"Urraan is a digital gateway"];
var i = 0;
var x = document.getElementById("demo");
var y = document.getElementById("newsArr1");
// var timeoutId;
function next() {
// if (timeoutId) {
// clearTimeout(timeoutId);
// }
i++;
if (i < newsArr.length) {
x.innerHTML = newsArr[i];
y.innerHTML = newsArr1[i];
} else {
i = 0;
x.innerHTML = newsArr[i];
y.innerHTML = newsArr1[i];
}
// timeoutId = setTimeout(next, 2000);
setThumbnailFocus(i)
}
function prev() {
i--;
if (i >= 0) {
x.innerHTML = newsArr[i];
y.innerHTML = newsArr1[i];
} else {
i = newsArr.length - 1;
x.innerHTML = newsArr[i];
y.innerHTML = newsArr1[i];
}
setThumbnailFocus(i)
}
function thumbchange(num) {
x.innerHTML = newsArr[num-1];
y.innerHTML = newsArr1[num-1];
setThumbnailFocus(num-1)
}
function setThumbnailFocus(num){
var elems = document.querySelectorAll(".thumbs .selected");
[].forEach.call(elems, function(el) {
el.classList.remove("selected");
});
document.getElementsByClassName("img12")[num].classList.add("selected");
}
.newsslider {
width: 100%;
height: 800px;
background-color:#766582;
}
.text {
text-align: center;
font-size: 40px;
color: white;
margin-bottom: -101px;
}
.btn1,
.btn2 {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
margin-top: -30px;
padding: 16px;
color: #52492f;
font-weight: bold;
font-size: 20px;
border-radius: 0 3px 3px 0;
user-select: none;
}
.btn2 {
position: absolute;
right: 0;
border-radius: 3px 0 0 3px;
}
.btn1:hover,
.btn2:hover {
background-color: rgba(0, 0, 0, 0.8);
color: white;
}
.onebtn {}
.twobtn {}
.thumbs {
display: flex;
padding-top: 6%;
align-items: center;
justify-content: center;
list-style: none;
}
.thumbs li {
width: 12%;
padding: 10px;
margin: 1%;
}
.thumbs li img {
width: 100%;
}
.img12:hover {
box-shadow: 0 0 2px 1px rgba(0, 140, 186, 0.5);
}
.selected{
border:solid 2px red
}
<div class="newsslider">
<p class="text" id="demo"><img id="demo1" src="https://www.w3schools.com/bootstrap4/la.jpg" width=100%; height=400px;> </p>
<div class="onebtn">
<button id="btn1" class="btn1" type="button" class="prev" onclick="prev()">PREV</button>
</div>
<div class="twobtn">
<button id="btn2" class="btn2" type="button" class="next" onclick="next()">NEXT</button>
</div>
<p id="newsArr1" class="text" style="font-size:40px; font-weight:bolder; color: #521d2c;">Hi,</p>
<ul class="thumbs">
<li class="img12 selected" onclick="thumbchange(1)"><img src="https://www.w3schools.com/bootstrap4/la.jpg" width=500%;></li>
<li class="img12" onclick="thumbchange(2)"><img src="https://www.w3schools.com/bootstrap4/chicago.jpg"></li>
<li class="img12" onclick="thumbchange(3)"><img src="https://www.w3schools.com/bootstrap4/ny.jpg"></li>
</ul>
</div>
The first issue I found is that you have this code:
<p class="text" id="demo"><img id="demo1" src="img5.png" width=30%; height=400px;> </p>
And here you didn't use part with setting id:
var newsArr = ['<img //here is no id// src="img5.png"width = 30%; height=400px;>',
'<img //here is no id// src="img2.png"width = 30%; height=400px; >',
'<img //here is no id// src="img4.png" width = 30%; height=400px;>'];
And when you are clicking on next and prev button, you are removing your id unconsciously, so your thumbchange() function stop working, because it is based on id.

How to color the right choice and the wrong choice in java script quiz?

I want to color the button with green when user choice the correct answer, and with red when it is wrong but in a same time with color the correct answer with green i try this but it is not work.
this text is to let me to publish the post
/*
I would like to be able to show the user what the correct answer to the question is if the one that they selected was incorrect. I would like to keep it simple, but here is what I am thinking. Once the user submits their answer and if it is incorrect, before moving onto the next question I would like for the incorrect answer to be highlighted in red, and the correct answer to be highlighted in green.
I already have coded whether or not the answer is correct or incorrect, but I haven't been able to figure out how to be able to show the correct answer if an incorrect one is chosen.
*/
function wait(ms){
var start = new Date().getTime();
var end = start;
while(end < start + ms) {
end = new Date().getTime();
}
}
function Quiz(questions) {
this.score = 0;
this.questions = questions;
this.questionIndex = 0;
}
Quiz.prototype.getQuestionIndex = function() {
return this.questions[this.questionIndex];
}
Quiz.prototype.guess = function(answer) {
if(this.getQuestionIndex().isCorrectAnswer(answer)) {
console.log(answer);
this.score++;
}
populateV2();
wait(2000);
this.questionIndex++;
}
Quiz.prototype.isEnded = function() {
return this.questionIndex === this.questions.length;
}
function Question(text, textAnswer, choices, answer) {
this.text = text;
this.textAnswer = textAnswer;
this.choices = choices;
this.answer = answer;
}
Question.prototype.isCorrectAnswer = function(choice) {
document.getElementById("btn0").style.backgroundColor='green';
return this.answer === choice;
}
function populate() {
if(quiz.isEnded()) {
showScores();
}
else {
// show question
var element = document.getElementById("question");
element.innerHTML = quiz.getQuestionIndex().text;
// show textAnswer
var textAnswer = quiz.getQuestionIndex().textAnswer;
for(var i = 0; i < textAnswer.length; i++) {
var element = document.getElementById("textAnswer" + i);
element.innerHTML = textAnswer[i];
}
// show options
var choices = quiz.getQuestionIndex().choices;
for(var i = 0; i < choices.length; i++) {
var element = document.getElementById("choice" + i);
element.innerHTML = choices[i];
guess("btn" + i, choices[i]);
}
showProgress();
}
};
function populateV2() {
console.log("Test");
// show question
var element = document.getElementById("question");
element.innerHTML = quiz.getQuestionIndex().text;
// show textAnswer
var textAnswer = quiz.getQuestionIndex().textAnswer;
for(var i = 0; i < textAnswer.length; i++) {
var element = document.getElementById("textAnswer" + i);
element.innerHTML = textAnswer[i];
}
// show options
var choices = quiz.getQuestionIndex().choices;
for(var i = 0; i < choices.length; i++) {
var element = document.getElementById("choice" + i);
element.innerHTML = choices[i];
}
showProgress();
};
function guess(id, guess) {
var button = document.getElementById(id);
button.onclick = function() {
quiz.guess(guess);
populate();
}
};
function showProgress() {
var currentQuestionNumber = quiz.questionIndex + 1;
var element = document.getElementById("progress");
element.innerHTML = "Question " + currentQuestionNumber + " of " + quiz.questions.length;
};
function showScores() {
var gameOverHTML = "<h1>Result</h1>";
gameOverHTML += "<h2 id='score'> Your scores: " + quiz.score + "</h2>";
var element = document.getElementById("quiz");
element.innerHTML = gameOverHTML;
};
// create questions here
var questions = [
new Question("1.At what age was Harry Potter when he received his Hogwarts letter?",
["A: 9",
"B: 6",
"C: 7"],
["A", "B","C"],
"C"),
new Question("2.Which is not a Hogwarts house?",
["A: Dunder Mifflin",
"B: Ravenclaw",
"C: Slytherin"],
["A", "B","C"],
"A"),
new Question("3.Who teaches Transfiguration at Hogwarts?",
["A: Rubeus Hagrid",
"B: Minerva McGonnagle",
"C: Albus Dumbledore"],
["A", "B","C"],
"B")
];
// create quiz
var quiz = new Quiz(questions);
// display quiz
populate();
body {
background-color: #eeeeee;
}
.grid {
width: 600px;
height: 600px;
margin: 0 auto;
background-color: #fff;
padding: 10px 50px 50px 50px;
border-radius: 50px;
border: 2px solid #cbcbcb;
box-shadow: 10px 15px 5px #cbcbcb;
}
.grid h1 {
font-family: "sans-serif";
background-color: #57636e;
font-size: 60px;
text-align: center;
color: #ffffff;
padding: 2px 0px;
border-radius: 50px;
}
#score {
color: #5A6772;
text-align: center;
font-size: 30px;
}
.grid #question {
font-family: "monospace";
font-size: 20px;
color: #5A6772;
}
.grid1 #textAnswer {
font-family: "monospace";
font-size: 15px;
color: #5A6772;
}
.image {
width: 20%;
}
.buttons {
margin-top: 30px;
}
#btn0, #btn1 {
background-color: #778897;
width: 250px;
font-size: 20px;
color: #fff;
border: 1px solid #1D3C6A;
border-radius: 50px;
margin: 10px 40px 10px 0px;
padding: 10px 10px;
}
#btn2 {
background-color: #778897;
width: 500px;
font-size: 20px;
color: #fff;
border: 1px solid #1D3C6A;
border-radius: 50px;
margin: 10px 40px 10px 20px;
padding: 10px 10px;
}
#btn0:hover, #btn1:hover, #btn2:hover {
cursor: pointer;
background-color: #57636e;
}
#btn0:focus, #btn1:focus, #btn2:focus {
outline: 0;
}
#progress {
color: #2b2b2b;
font-size: 18px;
}
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Quiz</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="grid">
<div id="quiz">
<h1>Quiz</h1>
<hr style="margin-bottom: 20px">
<p id="question"></p>
<ul class="grid1">
<li id="textAnswer0"></li>
<li id="textAnswer1"></li>
<li id="textAnswer2"></li>
</ul>
<div class="buttons">
<button id="btn0"><span id="choice0"></span></button>
<button id="btn1"><span id="choice1"></span></button>
<button id="btn2"><span id="choice2"></span></button>
</div>
<span id="wrong_answer"></span>
<hr style="margin-top: 50px">
<footer>
<p id="progress">Question x of y</p>
</footer>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
In order to color the right choice with green and the wrong choices with red just select all buttons, compare the content of their <span> element with the right answer and color them accordingly:
function wait(ms) {
var start = new Date().getTime();
var end = start;
while (end < start + ms) {
end = new Date().getTime();
}
}
function Quiz(questions) {
this.score = 0;
this.questions = questions;
this.questionIndex = 0;
}
Quiz.prototype.getQuestionIndex = function() {
return this.questions[this.questionIndex];
}
Quiz.prototype.guess = function(answer) {
if (this.getQuestionIndex().isCorrectAnswer(answer)) {
console.log(answer);
this.score++;
}
populateV2();
wait(2000);
this.questionIndex++;
}
Quiz.prototype.isEnded = function() {
return this.questionIndex === this.questions.length;
}
function Question(text, textAnswer, choices, answer) {
this.text = text;
this.textAnswer = textAnswer;
this.choices = choices;
this.answer = answer;
}
Question.prototype.isCorrectAnswer = function(choice) {
var answer = this.answer;
const buttons = document.querySelectorAll('button');
for (let i = 0; i < buttons.length; i++) {
var letter = buttons[i].getElementsByTagName("span")[0].textContent;
if (letter == answer) {
buttons[i].style.backgroundColor = 'green';
} else {
buttons[i].style.backgroundColor = 'red';
}
}
return this.answer === choice;
}
function populate() {
if (quiz.isEnded()) {
showScores();
} else {
// show question
var element = document.getElementById("question");
element.innerHTML = quiz.getQuestionIndex().text;
// show textAnswer
var textAnswer = quiz.getQuestionIndex().textAnswer;
for (var i = 0; i < textAnswer.length; i++) {
var element = document.getElementById("textAnswer" + i);
element.innerHTML = textAnswer[i];
}
// show options
var choices = quiz.getQuestionIndex().choices;
for (var i = 0; i < choices.length; i++) {
var element = document.getElementById("choice" + i);
element.innerHTML = choices[i];
guess("btn" + i, choices[i]);
}
showProgress();
}
};
function populateV2() {
console.log("Test");
// show question
var element = document.getElementById("question");
element.innerHTML = quiz.getQuestionIndex().text;
// show textAnswer
var textAnswer = quiz.getQuestionIndex().textAnswer;
for (var i = 0; i < textAnswer.length; i++) {
var element = document.getElementById("textAnswer" + i);
element.innerHTML = textAnswer[i];
}
// show options
var choices = quiz.getQuestionIndex().choices;
for (var i = 0; i < choices.length; i++) {
var element = document.getElementById("choice" + i);
element.innerHTML = choices[i];
}
showProgress();
};
function guess(id, guess) {
var button = document.getElementById(id);
button.onclick = function() {
quiz.guess(guess);
populate();
}
};
function showProgress() {
var currentQuestionNumber = quiz.questionIndex + 1;
var element = document.getElementById("progress");
element.innerHTML = "Question " + currentQuestionNumber + " of " + quiz.questions.length;
};
function showScores() {
var gameOverHTML = "<h1>Result</h1>";
gameOverHTML += "<h2 id='score'> Your scores: " + quiz.score + "</h2>";
var element = document.getElementById("quiz");
element.innerHTML = gameOverHTML;
};
// create questions here
var questions = [
new Question("1.At what age was Harry Potter when he received his Hogwarts letter?",
["A: 9",
"B: 6",
"C: 7"
],
["A", "B", "C"],
"C"),
new Question("2.Which is not a Hogwarts house?",
["A: Dunder Mifflin",
"B: Ravenclaw",
"C: Slytherin"
],
["A", "B", "C"],
"A"),
new Question("3.Who teaches Transfiguration at Hogwarts?",
["A: Rubeus Hagrid",
"B: Minerva McGonnagle",
"C: Albus Dumbledore"
],
["A", "B", "C"],
"B")
];
// create quiz
var quiz = new Quiz(questions);
// display quiz
populate();
body {
background-color: #eeeeee;
}
.grid {
width: 600px;
height: 600px;
margin: 0 auto;
background-color: #fff;
padding: 10px 50px 50px 50px;
border-radius: 50px;
border: 2px solid #cbcbcb;
box-shadow: 10px 15px 5px #cbcbcb;
}
.grid h1 {
font-family: "sans-serif";
background-color: #57636e;
font-size: 60px;
text-align: center;
color: #ffffff;
padding: 2px 0px;
border-radius: 50px;
}
#score {
color: #5A6772;
text-align: center;
font-size: 30px;
}
.grid #question {
font-family: "monospace";
font-size: 20px;
color: #5A6772;
}
.grid1 #textAnswer {
font-family: "monospace";
font-size: 15px;
color: #5A6772;
}
.image {
width: 20%;
}
.buttons {
margin-top: 30px;
}
#btn0, #btn1 {
background-color: #778897;
width: 250px;
font-size: 20px;
color: #fff;
border: 1px solid #1D3C6A;
border-radius: 50px;
margin: 10px 40px 10px 0px;
padding: 10px 10px;
}
#btn2 {
background-color: #778897;
width: 500px;
font-size: 20px;
color: #fff;
border: 1px solid #1D3C6A;
border-radius: 50px;
margin: 10px 40px 10px 20px;
padding: 10px 10px;
}
#btn0:hover, #btn1:hover, #btn2:hover {
cursor: pointer;
background-color: #57636e;
}
#btn0:focus, #btn1:focus, #btn2:focus {
outline: 0;
}
#progress {
color: #2b2b2b;
font-size: 18px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="grid">
<div id="quiz">
<h1>Quiz</h1>
<hr style="margin-bottom: 20px">
<p id="question"></p>
<ul class="grid1">
<li id="textAnswer0"></li>
<li id="textAnswer1"></li>
<li id="textAnswer2"></li>
</ul>
<div class="buttons">
<button id="btn0"><span id="choice0"></span></button>
<button id="btn1"><span id="choice1"></span></button>
<button id="btn2"><span id="choice2"></span></button>
</div>
<span id="wrong_answer"></span>
<hr style="margin-top: 50px">
<footer>
<p id="progress">Question x of y</p>
</footer>
</div>
</div>
Note that you have to adjust/restructure your code so that there's a short waiting time before the new question is generated as I think you might want to show the buttons again with the grey background color upon a new question.

want to give a fix position to button and list text

function enterToSubmit(event){
var key = event.keyCode;
if(key===13){
add();
}
}
function get_todos() {
var todos = new Array;
var todos_str = localStorage.getItem('todo');
if (todos_str !== null) {
todos = JSON.parse(todos_str);
}
return todos;
}
function add() {
var task = document.getElementById('task').value;
var todos = get_todos();
todos.push(task);
localStorage.setItem('todo', JSON.stringify(todos));
show();
return false;
}
function remove() {
var id = this.getAttribute('id');
var todos = get_todos();
todos.splice(id, 1);
localStorage.setItem('todo', JSON.stringify(todos));
show();
return false;
}
function show() {
var todos = get_todos();
var html = '<ul>';
for(var i=0; i<todos.length; i++) {
html += '<li>' + todos[i] + '<button class="remove" id="' + i + '">x</button></li>';
};
html += '</ul>';
document.getElementById('todos').innerHTML = html;
var buttons = document.getElementsByClassName('remove');
for (var i=0; i < buttons.length; i++) {
buttons[i].addEventListener('click', remove);
};
}
document.getElementById('add').addEventListener('click', add);
show();
*{
margin: 0px;
padding: 0px;
background-color: aqua;
}
#a{
align-content: center;
text-align: center;
background-color: lime;
}
input:focus{
border-color: aqua;
}
input{
margin: 30px 0px 30px 30px;
border-radius: 35%;
padding-top: 20px;
padding-left: 50px;
padding-right: 50px;
padding-bottom: 20px;
color: aqua;
background-color: rgb(255, 0, 64);
font-size: 20px;
text-align: center;
}
#add,button{
font-size: large;
border-radius: 30%;
background-color: rgb(255, 0, 64);
color: white;
padding: 10px;
margin-bottom: 0px;
margin-top: 0px;
margin-left: 10px;
}
#todos{
}
button{
padding-right: 18px;
padding-left: 18px;
}
li{
font-size: 25px;
border: 10px solid black;
margin: 5px;
padding: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<DOCTYPE html>
<html lang="en">
<head>
<title>TODO List</title>
<link rel="stylesheet" href="nv.css">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
</head>
<body>
<div id="a">
<input id="task" onkeypress="enterToSubmit(event)"><button id="add">Add</button>
</div>
<hr>
<div id="todos">
</div>
<script src="nv.js"></script>
</body>
</html>
I am making a todo list wab app in javascript html and css and when i insert any element or task it take position according to length of task but i want all button and task in a parallel line
HTML Code :- https://textuploader.com/1oyu3
CSS Code :- https://textuploader.com/1oyuy
JS Code :- https://textuploader.com/1oyui
Img:-current img
Img:-what i want
Thanks
here you can see full at jsfiddle
i add div at your javascript
for(var i=0; i<todos.length; i++) {
html += '<li><div class="list">' + todos[i] + '</div><div class="button"><button class="remove" id="' + i + '">x</button></div></li>';
};
and make add css with class list & button
.list{
float: left;
width: 80%;
text-align: center;
}
.button{
float: left;
width: 20%;
text-align: right;
}
li{
display: flex;
}
change nv.js
function enterToSubmit(event){
var key = event.keyCode;
if(key===13){
add();
}
}
function get_todos() {
var todos = new Array;
var todos_str = localStorage.getItem('todo');
if (todos_str !== null) {
todos = JSON.parse(todos_str);
}
return todos;
}
function add() {
var task = document.getElementById('task').value;
var todos = get_todos();
todos.push(task);
localStorage.setItem('todo', JSON.stringify(todos));
show();
return false;
}
function remove() {
var id = this.getAttribute('id');
var todos = get_todos();
todos.splice(id, 1);
localStorage.setItem('todo', JSON.stringify(todos));
show();
return false;
}
function show() {
var todos = get_todos();
var html = '<ul>';
for(var i=0; i<todos.length; i++) {
html += '<li><span class="todoname">' + todos[i] + '</span><button class="remove" id="' + i + '">x</button></li>'; // add span in name for css
};
html += '</ul>';
document.getElementById('todos').innerHTML = html;
var buttons = document.getElementsByClassName('remove');
for (var i=0; i < buttons.length; i++) {
buttons[i].addEventListener('click', remove);
};
}
document.getElementById('add').addEventListener('click', add);
show();
nv.css
li{
font-size: 25px;
border: 10px solid black;
margin: 5px;
padding: 5px;
height:50px; // add height in li
}
/* add this classes in your css */
.remove
{
float:right;
}
.todoname
{
margin-left: 100px;
vertical-align: middle;
}

JS Can't update a value in HTML connected to a value in an array of objects

I'm trying to update the value inside an array of objects using this
syntax: array[objectindex].key = array[objectindex].key + 1;
on console.log work perfectly taking the value from the object, the problem is the value in the object isn't updated.
I'm trying to update SCORE BOARDS with a function inside MATCHING.
I use that value as a scoring point in HTML.
//-----------------CARDS DECK--------------------
var cards = [
{
rank:"Queen",
suit: "Hearts",
cardImage: "images/queen-of-hearts.png"
},
{
rank: "Queen",
suit: "Dimonds",
cardImage: "images/queen-of-diamonds.png"
},
{rank: "King",
suit: "Hearts",
cardImage: "images/king-of-hearts.png"
},
{
rank: "King",
suit: "Diamonds",
cardImage: "images/king-of-diamonds.png"
}
];
//-----------------SCORE BOARDS-----------------
var score = [
{
points:0,
parent: 'left-board',
side:"p1"
},
{
points:0,
parent:'right-board',
side:"ai"
}
];
var cardsInPlay = [];
//----------------CREATE THE GAMEBOARD-----------
var createBoard = function () {
for (var i=0; i < cards.length; i++) {
var cardElement = document.createElement('img');
cardElement.setAttribute('src','images/back.png');
cardElement.setAttribute('data-id',i);
cardElement.addEventListener('click',flipCard);
document.getElementById('game-board').appendChild(cardElement);
}
}
//--------------CREATE SCORE-------------------
var createScore = function () {
for (var i=0; i < score.length; i++) {
var scoreElement = document.createElement('div');
scoreElement.setAttribute('class','points');
scoreElement.setAttribute('id',score[i].side);
document.getElementById(score[i].parent).appendChild(scoreElement);
document.getElementById(score[i].side).innerHTML=score[i].points;
}
}
//----------------FLIPCARD----------------------
var flipCard = function () {
var cardId = this.getAttribute("data-id");
console.log("User flipped over " + cards[cardId].rank);
console.log(cards[cardId].suit);
console.log(cards[cardId].cardImage);
cardsInPlay.push(cards[cardId].rank);
this.setAttribute('src',cards[cardId].cardImage);
if (cardsInPlay.length === 2) {
setTimeout(checkForMatch,300);
//reset();
}
}
//----------------MATCHING------------------------
function checkForMatch() {
if (cardsInPlay[0] === cardsInPlay[1]) {
alert("You found a match!");
score[0].points ++;
console.log(score[0]);
}
else {
alert("Sorry, try again.");
}
}
//----------------GAME RESET---------------------
var reset = function () {
for (var i=0; i < cards.length; i++) {
document.getElementsByTagName('img')[i].setAttribute('src','images/back.png');
}
cardsInPlay = [];
}
//##############---INVOKING----#####################
createScore();
createBoard();
//score[0].points =
console.log(score[0].points);
body {
text-align: center;
margin: 0;
}
h1 {
font-family: Raleway;
color: white;
letter-spacing: 1px;
font-weight: 400;
font-size: 45px;
margin: 0;
}
a {
font-family: Raleway;
letter-spacing: 1px;
font-weight: 400;
font-size: 18px;
border-bottom: 2px solid transparent;
}
a:hover {
border-bottom: 2px solid white;
}
h2 {
font-family: Raleway;
color: #0d2c40;
letter-spacing: 1px;
font-weight: 600;
font-size: 20;
}
p {
font-family: "Droid Serif";
line-height: 26px;
font-size: 18px;
}
header {
background-color: #F15B31;
padding: 30px 20px;
}
main {
width: auto;
margin: 35px auto;
}
nav {
background: #00A6B3;
padding:20px 0;
}
.navlink {
margin:0 20px;
color: white;
}
img {
margin: 20px 8px;
}
footer {
background-color:#0D2C40;
text-transform: uppercase;
padding: 0 20px;
color: white;
font-size: 14px;
letter-spacing: .08em;
font-weight: 500;
}
.copyright {
font-family: Raleway, sans-serif;
float: left;
}
.message{
font-family: Raleway, sans-serif;
float: right;
}
.clearfix:after {
visibility: hidden;
display: block;
content: " ";
clear: both;
height: 0;
font-size: 0;
padding: 0;
}
.name {
color:#F15B31;
font-weight: 700;
}
.point-board {
border-style: solid;
position: absolute;
width: 150px;
height: 150px;
border-radius: 90px;
line-height: 100px;
text-align: center;
font-family: Raleway;
}
#left-board {
top: 630px;
left: 70px;
}
#right-board {
top: 630px;
left: 1152px;
}
.points {
margin: -50px;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Droid+Serif|Raleway:400,500,600,700" rel="stylesheet">
<title>Marco's memory game</title>
</head>
<body>
<header>
<h1>Marco's memory game</h1>
</header>
<nav>
<a class="navlink" href="#instructions">Instructions</a>
<a class="navlink" href="#facts">Game facts</a>
<a class="navlink" href="#game-board">Play!</a>
</nav>
<main>
<h2 id="instructions">Instructions</h2>
<p>Concentration, also known as Match Match, Memory, Pelmanism, Shinkei-suijaku, Pexeso or simply Pairs, is a card game
in which all of the cards are laid face down on a surface and two cards are flipped face up over each turn. The
object of the game is to turn over pairs of matching cards.</p>
<h2 id="facts">Game's facts</h2>
<p>An other popular memory game is called "Kim's game. Kim's Game is a game or exercise played by Boy Scouts, Girl Scouts
and Girl Guides, and other children's groups.[1] The game develops a person's capacity to observe and remember
details. The name is derived from Rudyard Kipling's 1901 novel Kim, in which the hero, Kim, plays the game during
his training as a spy.
More info...
</p>
<div class="point-board" id="left-board">PLAYER
<div class="points" id= "p1"></div>
</div>
<h2>Play!</h2>
<div id="game-board" class="board clearfix"></div>
<div class="point-board" id="right-board">AI
<div class="points" id= "ai">00</div>
</div>
</main>
<footer class="clearfix">
<p class="copyright">Copyright 2017</p>
<p class="message">Created with ♥ by <span class="name"> GA </span></p>
</footer>
<script src="js/main.js"></script>
</body>
</html>
I'm not sure why your code isn't working, but you can use ++ to simplify that statement...
score[0].points++;
Solved!
function checkForMatch() {
if (cardsInPlay[0] === cardsInPlay[1]) {
alert("You found a match!");
document.getElementById('p1').innerHTML=score[0].points + 1;
console.log(score[0]);
}
else {
alert("Sorry, try again.");
}
}

Categories

Resources