Hi I would like to know how I can style these buttons in Javascript in my quiz.
I can't figure out how to do that. Would be great if someone can help.
Sample code is below and full code is further below. I tried doing making the buttons a div but that did not work.
Would be great if someone can help.
Sample code is below and full code is further below.
thank you
for(i=0; i < options.length; i++){
document.getElementById("trivia").innerHTML += "<br><button onclick='checkAnswer(\""+options[i]+"\", this)'>" + options[i] + "</button>";
}
}
// This initialises a request to the trivia database API
var xmlhttp = new XMLHttpRequest();
var url = "https://opentdb.com/api.php?amount=1&category=21&difficulty=easy&type=multiple";
var score = 0;
var livesTaken = 0;
var question;
var type;
var correctAnswer;
var incorrect1;
var incorrect2;
var incorrect3;
// This requests the data
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var jsondata = JSON.parse(this.responseText);
getData(jsondata);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
// This function is used to extract the received data
function getData(data) {
// This is the question:
question = data.results[0].question;
// This is the question type eg. multiple choice
type = data.results[0].type;
// This is the correct answer
correctAnswer = data.results[0].correct_answer;
// These are the three incorrect answers
incorrect1 = data.results[0].incorrect_answers[0];
incorrect2 = data.results[0].incorrect_answers[1];
incorrect3 = data.results[0].incorrect_answers[2];
// randomly select answer and other options and place in array
// then display elements from array on the buttons
var randoms = []; // an array to store unique random numbers
var random;
// loop runs four times...
for(i=0; i < 4; i++){
// generates a random number between 0 and 3
random = Math.floor(Math.random() * 4);
// checks if random number already in array...
while(randoms.includes(random)){
// generates another random number
random = Math.floor(Math.random() * 4);
}
// adds random number to array
randoms.push(random);
}
var options = [];
console.log(randoms);
options[randoms[0]] = correctAnswer;
options[randoms[1]] = incorrect1;
options[randoms[2]] = incorrect2;
options[randoms[3]] = incorrect3;
console.log(options);
// This displays the question and answer options
document.getElementById("trivia").innerHTML = question;
for(i=0; i < options.length; i++){
document.getElementById("trivia").innerHTML += "<br><button onclick='checkAnswer(\""+options[i]+"\", this)'>" + options[i] + "</button>";
}
}
function checkAnswer(selected, element){
console.log("User selected: " + selected);
console.log("The correct answer is: " + correctAnswer);
if(selected == correctAnswer){
score++;
console.log("You got it right!");
element.style.background = "green";
setTimeout(function(){
getNewQuestion();
}, 2000);
}
else{
livesTaken ++;
console.log("Sorry, that's incorrect");
element.style.background = "red";
if(livesTaken ==3){
quizFailed();
}else{
setTimeout(function(){
getNewQuestion();
}, 450);
}
}
console.log(score)
console.log(livesTaken)
}
function getNewQuestion(){
document.getElementById("score").style.display = "block";
document.getElementById("score").style.float = "right";
document.getElementById("trivia").style.float = "left";
document.getElementById("score").style.align = "right";
document.getElementById("score").innerHTML = "score:" + score;
document.getElementById("trivia").style.display = "block";
document.getElementById("endingText").style.display = "none";
// This requests the data
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var jsondata = JSON.parse(this.responseText);
getData(jsondata);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
} getNewQuestion()
function quizFailed(){
document.getElementById("endingText").style.display = "block"
document.getElementById("score").style.display = "none"
document.getElementById("trivia").style.display = "none"
document.getElementById("endingText").innerHTML = "You have run out of lives, you scored " + score + " pretty bad ngl" + " <button onClick = getNewQuestion() >click to restart</button>"
score = 0;
livesTaken = 0;
}
document.getElementById("score")
<html>
<head>
<link rel="stylesheet" href="Actualquiz.css">
<title>Sport Quiz (Medium)</title>
<meta charset="utf-8" />
<script src="script.js"></script>
<div id="trivia"></div>
<div id ="endingText"></div>
<div id ="score"></div>
</head>
<body>
</body>
</html>
If this is the line where you create the btns
for(i=0; i < options.length; i++){
document.getElementById("trivia").innerHTML += "<br><button onclick='checkAnswer(\""+options[i]+"\", this)'>" + options[i] + "</button>";
}
I suggest you to opt for another way, something like this would be a bit better.
for(i=0; i < options.length; i++) {
let btn = document.createElement("button");
// You can now style it like so
btn.style.backgroundColor = "blue" // This is an example, you can use any css styling.
btn.style.padding: 0.7rem 2rem;
btn.style.color = "white";
btn.style.marginTop = ".4rem";
btn.setAttribute("onclick", `checkAnswer("${options[i]}", this)`);
btn.innerHTML = options[i];
let br = document.createElement("br");
document.getElementById("trivia").append(br, btn); // You can now use the trivia div as a container for the generated button and your br
}
}
But as you can see there's a lot of extra code to just style the button, so what I'd do is create a class with the preferred stylings, and apply it in the js, like so:
JS file
for(i=0; i < options.length; i++) {
let btn = document.createElement("button");
let br = document.createElement("br");
btn.classList.add("trivia-btn"); // We're adding the class here
btn.setAttribute("onclick", `checkAnswer("${options[i]}", this)`);
btn.innerHTML = options[i];
document.getElementById("trivia").append(br, btn); // You can now use the trivia div as a container for the generated button and your br
}
}
CSS file
.trivia-btn {
background-color: "blue";
padding: 0.7rem 2rem;
color: white;
margin-top: 0.4rem;
}
My css example is a bit ugly but of course you can choose any css styling you want, or a framework to use premade classes.
Related
I'm doing a little game that is about a questions-answers game, that has 3 options and only one is the right one. So, what I'm trying to do is, every time I open the page, I randomize the correct answer, so, the player can't just memorize the positions, he will be obligate to remember the true answer. I already know how to randomize the right button, doing it with a random number and stuff like that, but, with this problem, just randomize the right button isn't what I need, cuz I have to change the position of the answer too. So, this is my code.
const vintecinco = document.getElementById('312');
const vinteseis = document.getElementById('314');
const vintesete = document.getElementById('214');
vinteseis.addEventListener('click', acerto);
function acerto() {
var msg = document.createElement('p');
msg.textContent = 'Voce acertou!';
msg.style.cssText = 'color: green;'
document.body.appendChild(msg);
var prosseguir = document.createElement('a');
prosseguir.textContent = 'Próxima pergunta!'
prosseguir.href = 'q3.html';
document.body.appendChild(prosseguir);
vintecinco.disabled = true;
vinteseis.disabled = true;
vintesete.disabled = true;
}
vintecinco.addEventListener('click', erro);
vintesete.addEventListener('click', erro);
function erro() {
var msgerro = document.createElement('p');
msgerro.textContent = "Voce errou!";
msgerro.style.cssText = 'color: red;';
document.body.appendChild(msgerro);
var voltar = document.createElement('a');
voltar.textContent = 'Recomeçar!'
voltar.href = 'index.html';
document.body.appendChild(voltar);
vintecinco.disabled = true;
vinteseis.disabled = true;
vintesete.disabled = true;
}
<main>
<p>Qual o número de pi?</p>
<input type="submit" value="3,12..." id='312'>
<input type="submit" value="2,14..." id='214'>
<input type="submit" value="3,14..." id='314'>
</main>
What kind of thing I could do to get random positions without compromise my right answer?
Now I did some changes and I created a test file. I'm trying to do something like that, but now, I can't change the value of the 2 wrong answers, they're default. How could I change it?
var random = Math.floor(Math.random() * 3);
for(var i=1;i<=10;i++) {
console.log(i);
var button = document.getElementById('btn' + i);
if(random == i) {
button.addEventListener('click', prize);
button.value = '1';
}
else {
button.addEventListener('click', closewindow);
button.value = '2';
}
}
There are many ways to do what you want, depending on the rest of the application, one or the other may be better for you, an example:
var input = [];
function acerto() {
var msg = document.createElement('p');
msg.textContent = 'Voce acertou!';
msg.style.cssText = 'color: green;'
document.body.appendChild(msg);
var prosseguir = document.createElement('a');
prosseguir.textContent = 'Próxima pergunta!'
prosseguir.href = 'q3.html';
document.body.appendChild(prosseguir);
input.forEach((i)=>{
i.disabled = true;
});
input = [];
}
function erro() {
var msgerro = document.createElement('p');
msgerro.textContent = "Voce errou!";
msgerro.style.cssText = 'color: red;';
document.body.appendChild(msgerro);
var voltar = document.createElement('a');
voltar.textContent = 'Recomeçar!'
voltar.href = 'index.html';
document.body.appendChild(voltar);
input.forEach((i)=>{
i.disabled = true;
});
input = [];
}
// question, true, false, false...
var res = ["Qual o número de pi?", "3.14", "2.14", "3.12"];
var quest = document.getElementsByTagName("main")[0];
// Create Question
quest.innerHTML = "<p>" + res.splice(0, 1)[0] + "</p>";
// Create Random input
for(i in res){
let temp = document.createElement('input');
temp.type = "submit";
temp.value = res[i];
if(i == 0){
temp.addEventListener('click', acerto);
}else{
temp.addEventListener('click', erro);
}
let rand = Math.floor((input.length+1) * Math.random());
input.splice(rand, 0, temp);
}
// Show input
input.forEach((i)=>{
quest.appendChild(i);
});
<main>
</main>
Surely there must be a way to add some color to the line in the code below where it shows m.codeletters = "&#+%?£#§$"; etc? I want to change the color to : **"&#+%?£#§$"**
var Messenger = function(el){
'use strict';
var m = this;
m.init = function(){
m.codeletters = "&#*+%?£#§$";
m.message = 0;
m.current_length = 0;
m.fadeBuffer = false;
m.messages = [
'readers',
'via feed',
'👽'
];
setTimeout(m.animateIn, 100);
};
m.generateRandomString = function(length){
var random_text = '';
while(random_text.length < length){
random_text += m.codeletters.charAt(Math.floor(Math.random()*m.codeletters.length));
}
return random_text;
};
m.animateIn = function(){
if(m.current_length < m.messages[m.message].length){
m.current_length = m.current_length + 2;
if(m.current_length > m.messages[m.message].length) {
m.current_length = m.messages[m.message].length;
}
var message = m.generateRandomString(m.current_length);
$(el).html(message);
setTimeout(m.animateIn, 20);
} else {
setTimeout(m.animateFadeBuffer, 20);
}
};
m.animateFadeBuffer = function(){
if(m.fadeBuffer === false){
m.fadeBuffer = [];
for(var i = 0; i < m.messages[m.message].length; i++){
m.fadeBuffer.push({c: (Math.floor(Math.random()*12))+1, l: m.messages[m.message].charAt(i)});
}
}
var do_cycles = false;
var message = '';
for(var i = 0; i < m.fadeBuffer.length; i++){
var fader = m.fadeBuffer[i];
if(fader.c > 0){
do_cycles = true;
fader.c--;
message += m.codeletters.charAt(Math.floor(Math.random()*m.codeletters.length));
} else {
message += fader.l;
}
}
$(el).html(message);
if(do_cycles === true){
setTimeout(m.animateFadeBuffer, 20);
} else {
setTimeout(m.cycleText, 2000);
}
};
m.cycleText = function(){
m.message = m.message + 1;
if(m.message >= m.messages.length){
m.message = 0;
}
m.current_length = 0;
m.fadeBuffer = false;
$(el).html('');
setTimeout(m.animateIn, 200);
};
m.init();
}
console.clear();
var messenger = new Messenger($('#messenger'));
I have looked up and down, to try and see where in the code I can do this. I also want to know what I need to add to be able to do this. I simply have no clue. I've seen other codes of similar where the codeletter area is colored, then the rest of the text another color.
If you're trying to color console output, you would use ANSI escape sequences that look something like this \u001b[31;1m, and which you can learn more about in this SO post. There is also an npm module available called colors that greatly simplifies the process of implementing them.
If you're trying to color HTML output, you would just wrap each character in an individual <span> element and add a class or style attribute with CSS-styling for the desired color.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I was doing an exercise I found on MDN website and I couldn't finish this one. The point is to use JSON, extract data from it and then display it on the page. The code works, it generates the strings as it should, I checked the console and everything is as it is supposed to be. It just won't assign the generated strings to the textContent properties of created paragraphs. When I do the same assignment in the console it works perfectly.
"""
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<section>
</section>
<script>
const section = document.querySelector('section');
let requestURL = "https://raw.githubusercontent.com/mdn/learning-area/master/javascript/oojs/tasks/json/sample.json";
let request = new XMLHttpRequest();
request.open("GET", requestURL);
request.responseType = "json";
request.send();
let kittenInfo;
let motherInfo = "The mothers are";
request.onload = function() {
let catString = request.response;
extractInfo(catString);
}
function extractInfo(info){
let end = ", ";;
let total = 0;
let male = 0;
let names = "";
for (let i = 0; i < info.length; i++) {
if (i === info.length - 2) {
end = " and";
}else if (i === info.length - 1){
end = ".";
}
motherInfo += " " + info[i].color + " " + info[i].breed + " " + info[i].name + end;
for (let j = 0; j < info[i].kittens.length; j++) {
end = ",";
if (i === info.length - 1) {
if (j === info[i].kittens.length - 2){
end = " and";
}else if (j === info[i].kittens.length - 1){
end = ".";
}
}
if (info[i].kittens[j].gender === "m"){
male += 1;
}
names += " " + info[i].kittens[j].name + end;
total += 1;
}
}
kittenInfo = `There are ${total} kittens, ${male} of them are male and ${total - male} of them are female. ` +
`Their names are ${names}`;
}
let para1 = document.createElement("p");
let para2 = document.createElement("p");
para1.textContent = motherInfo;
para2.textContent = kittenInfo;
section.appendChild(para1);
section.appendChild(para2);
</script>
</body>
</html>
You're setting the text content before you have the response from the HTTP request.
You'll need to move the para1.textContent = ..., etc., to inside your extractInfo() function.
This might seem insanely basic. But I'm struggling with this simple creation of an for-loop since no p Element is created on any loop-iteration. I don't know how to display the newly created p Element in my div Element (.output).
It should create an p element to my div on each iteration, showing the current value of i. When it's 10, it should say something like "Countdown has started" and at the end "Countdown Ended!". Here is a small sample (rest of html omitted):
<div class="output"></div>
<script>
let output = document.querySelector(".output");
output.innerHTML = '';
countBegin= "Countdown has started";
countEnd = "Countdown has ended";
countBet = "Countdown at ";
function countD() {
for (let i = 10; i<= 0; i--) {
var para = document.createElement("p");
if (i === 10) {
para.textContent = countBegin + i;
} else if (i === 0) {
para.textContent = countEnd;
} else {
para.textContent = countBet + i;
}
output.appendChild(para);
}
}
countD();
</script>
</body>
I would expect to see at least one line as an output in the browser window but sadly there isn't any.
Since you're looping from 10 to 0, the loop condition should be i >= 0:
let output = document.querySelector(".output");
output.innerHTML = '';
countBegin = "Countdown has started";
countEnd = "Countdown has ended";
countBet = "Countdown at ";
function countD() {
for (let i = 10; i >= 0; i--) {
var para = document.createElement("p");
if (i === 10) {
para.textContent = countBegin;
} else if (i === 0) {
para.textContent = countEnd;
} else {
para.textContent = countBet + i;
}
output.appendChild(para);
}
}
countD();
<div class="output"></div>
The program is a Seat reservation program rows 1 and 2 are first class, row 3-9 are business class and rows 10 through 13 are economy. They are initialized to * and become X when it is reserved. and alert you if the seat is already filled.
The rows will fill for the first 6 rows but it ignores request for row 7 and beyond. But i know it goes to the appropriate function because if i request Economy with row 3 (which is invalid) it alerts me. But if i ask for first class with row7 it will act like nothing has been requested.
It won't let me post the html code but it will display as row1-13 on the left and A - F across the top. I use drop down list and I set the values to the corresponding for the options to their corresponding spot in a the 2-d array (eg if i select row 5 and seat c the value of row 5 is 5 and the value of C is 3)
var rowSeat;
function start()
{
rowSeat = new Array(14);
for(var i = 0; i <rowSeat.length; i++)
{
rowSeat[i] = new Array(7);
}
var j = 65;
for(var i = 1; i <rowSeat[0].length; i++)
{
rowSeat[0][i] = String.fromCharCode(j);
j++;
}
rowSeat[0][0] = " ";
for(var i = 1; i <rowSeat.length; i++)
{
rowSeat[i][0] = "Row "+i;
}
for(var i = 1; i <rowSeat.length; i++)
{
for(var j = 1; j <rowSeat[i].length; j++)
{
rowSeat[i][j] = "*";
}
}
display();
var subButton = document.getElementById("submitButton");
subButton.addEventListener("click", assign, false);
}
function display()
{
var results = "";
results+="<table>"
for(var i in rowSeat)
{
results+="<tr>";
for(var j in rowSeat[i])
{
results += "<td>" +rowSeat[i][j]+ "</td>";
}
results += "</tr>";
}
results+="</table>"
var show2 = document.getElementById( "show2" );
show2.innerHTML = results;
}
function assign()
{
var inputField = document.getElementById("classAssign");
var classType = inputField.options[inputField.selectedIndex].value;
if (classType == "FirstClass")
{
fClassSearch();
}
else if (classType == "Business")
{
bClassSearch();
}
else
{
eClassSearch();
}
display();
}
function fClassSearch(){
var inputField = document.getElementById("seatAssign");
var seat = inputField.options[inputField.selectedIndex].value;
var inputField2 = document.getElementById("rowAssign");
var row = inputField.options[inputField2.selectedIndex].value;
var test = document.getElementById( "test" );
test.innerHTML = row +" "+ seat;
if (row >2){
var show2 = document.getElementById( "show" );
show.innerHTML = "Invalid choice only row 1 and 2 are First Class";
}
else {
if(rowSeat[row][seat] == "*")
{
rowSeat[row][seat] = "X";
show.innerHTML = "Your Seat choice was accepted and Reserved";
}
else{
show.innerHTML = "Your choice was already reserved please make another choice";
}
}
}
function bClassSearch(){
var inputField = document.getElementById("seatAssign");
var seat = inputField.options[inputField.selectedIndex].value;
var inputField2 = document.getElementById("rowAssign");
var row = inputField.options[inputField2.selectedIndex].value;
if (row <3 ||row >9){
var show2 = document.getElementById( "show" );
show.innerHTML = "Invalid choice only row 3 through 9 are BusinessClass";
}
else {
if(rowSeat[row][seat] == "*")
{
rowSeat[row][seat] = "X";
show.innerHTML = "Your Seat choice was accepted and Reserved";
}
else{
show.innerHTML = "Your choice was already reserved please make another choice";
}
}
}
function eClassSearch(){
var inputField = document.getElementById("seatAssign");
var seat = inputField.options[inputField.selectedIndex].value;
var inputField2 = document.getElementById("rowAssign");
var row = inputField.options[inputField2.selectedIndex].value;
var show1 = document.getElementById( "show" );
if (row <10){
show1.innerHTML = "Invalid choice only rows 10 through 13 are Economy Class";
}
else {
if(rowSeat[row][seat] == "*")
{
rowSeat[row][seat] = "X";
show.innerHTML = "Your Seat choice was accepted and Reserved";
}
else{
show.innerHTML = "Your choice was already reserved please make another choice";
}
}
}
window.addEventListener("load",start, false);
</script>
var row = inputField.options[inputField2.selectedIndex].value;
inputField.options should be inputField2.options
inputField.options only goes to 6 because you only have 6 seats wide, but you are trying to look at the row in the seat list.