0

I am looking for a way to disable buttons (answers) in a quiz game after an answer is chosen. I am also looking for a way to disable the counter from being incremented after an answer is chosen. One more problem is I tried linking fontawesome.com and other sites to use a simple icon and I only get empty squares for some reason.

I have no idea why I am unable to use disable property !! HELP U.U

<!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>Quiz</title>
    <link rel="stylesheet" href="style.css">
    <!-- <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous"> -->
    <!-- you can write script tag like this here -->
    <!-- <script defer src="srcript.js></script>"  (DEFER makes it load after the body) -->
    <script src="https://kit.fontawesome.com/1a0903df7b.js" crossorigin="anonymous"></script>

</head>
<body>
    <!-- container which wraps all content -->
    <div class="container">
        <i class="fas fa-crown"></i>
        <!-- Container to wrap the questions and answers -->
        <!-- class hide to which will be hidden by default-->
        <div id="question-Container" class="hide">
            <!-- div for the Question -->
            <div id="question">Question</div>
            <!-- div block for label and counter p -->
            <div id="block" class="blocks">
                <p id="correctAnswers">Answers: </p> 
                <p id="correctAnswer">0</p>
            </div>
            <!-- <p id="wrongAnswer">0</p> -->
            <!-- Div for Answers -->
            <div id="answer-buttons" class="btn-Grid">
                <button class="btn">Answer 1</button> <!-- "btn correct" -->
                <button class="btn">Answer 2</button> <!-- "btn wrong"-->
                <button class="btn">Answer 3</button>
                <button class="btn">Answer 4</button>
            </div>
        </div>
        <!-- Controls div for start and end -->
        <div class="controls">
            <!-- Shift+Alt+ DownArrow key || Up Arrow key to copy lines of code -->
            <button id="start-btn" class="start-btn btn">Start The Quiz</button>
            <!-- Hide property to keep it hidden -->
            <button id="next-btn" class="next-btn btn hide">Next Question</button>
        </div>
    </div>
    <script src="script.js"></script>
    <!--must call this here or with defer up-->
</body>
</html>
<!-- https://ogkcreative.com/development/8-html-css-tips-for-organizing-code-in-your-web-project/ -->

/* Here I will use border box to create my layout for universal use */
/* learned it from here : https://css-tricks.com/box-sizing/ */
*, *::before, *::after{
    box-sizing: border-box;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 1.5rem;
}
:root{
    --hue-neutral:200;  /*Blue  default*/
    --hue-wrong:0;      /*Red wrong answer*/
    --hue-correct:145;   /*Green correct answer*/
}

body{
    /* Hue  https://www.w3schools.com/colors/colors_hsl.asp
Hue is a degree on the color wheel from 0 to 360. 0 is red, 120 is green, 240 is blue.
Saturation is a percentage value; 0% means a shade of gray and 100% is the full color.
Lightness is also a percentage; 0% is black, 100% is white.
correct syntax hsl(h, s%, l%)

more on hue usage https://stackoverflow.com/questions/65478345/css-variable-calculation-of-hsl-values
we use hue to have more control over all color attributes separately


 how to declare global CSS variables here: https://developer.mozilla.org/en-US/docs/Web/CSS/:root         helped by Teacher Assistant Tariq
*/
    --hue: var(--hue-neutral);
    /* to move everything to the side */
    padding: 0;
    /* to move everything to the side */
    margin: 0;
    display: flex; /* to make it in center of screen */
    width: 100vw;  /*100vw and 100 vh makes it so you take 100% of the view of the width and height */
    height: 100vh;
    justify-content: center; /* to make it in center of screen */
    align-items: center; /* to make it in center of screen */
    background-color: hsl(var(--hue), 100%, 20%);
}

body.correct{
    --hue:var(--hue-correct);
}
body.wrong{
    --hue:var(--hue-wrong);
}
body.neutral{
    --hue: var(--hue-neutral);
}
/*no need to add class neutral since its auto blue default*/

.container{
    width: 800px;
    max-width: 80%; /* we add this to not allow content to overflow*/
    /* height:800px ; */
    /* max-height: 80%; */
    background-color: white;
    border-radius: 10px;
    padding: 10px;
    box-shadow: 0 0 10px 4px ;  /*x offset, y offset, blur, spread how far out it goes*/
}
.blocks{
    display: inline-flex;
     /* grid-template-rows: repeat(2, auto) ; */    
    gap: 10px;
    margin: 20px 0; 
}
.btn-Grid {
    display: grid; /* displays questions undernearth each other in columns*/
    grid-template-columns:repeat(2, auto); /*adds two cloumns for the questions*/
    gap: 10px; /*makes gap between questions*/
    margin: 20px 0; /* we add 20px margin top and bottom 0 left and right*/

}

.btn { /*generic will be applied to all buttons*/
--hue: var(--hue-neutral); /*assining var hue using it here*/
border: 1px solid hsl(var(--hue), 100%, 50%); /*adding border with solid attribute and color and 1px*/
background-color:hsl(var(--hue),100%,50%); /* changing bg color*/
border-radius: 5px; /*rounder radius*/
padding: 5px 10px; /*padding updown 5px leftright 10px*/
color: white;
outline: none;
}

.btn:hover{
    border-color: black; /*just change color of border to blck on mouse hover*/
    transition: 150ms;
    transform:scale(1.03);
}

.btn.correct {                         /*green bg and black color text*/
--hue:var(--hue-correct);
color:black;
}
.btn.wrong{                            /*red bg*/
--hue:var(--hue-wrong);
}

.start-btn{                            /*some css for start btn*/
font-size: 1.5rem;
font-weight: bold;
padding: 10px 30px;
margin:5px;
}

.next-btn{                              /*some css for next btn*/
    font-size: 1.5rem;
    font-weight: bold;
    padding: 10px 30px;
    margin:5px;
}
.controls {   /* corrects start next buttons to be in center*/
    display: flex;
    justify-content: center;
    align-items: center;

}

.hide {  /*hide class will hide everything until we show it with js after we click start*/
display: none;
}
/* Change colors and layout to be nicer!!!!!!!! important*/
/*to do add label css for the score counter*/
/*to do add label css for the timer counter " assuming time left to answer Q is 30 seconds" */
/*to do resize content */
/*add icons*/
/*add sound on correct / on wrong / on finish*/
/*add meaningfull entrypage*/


// I need to make functions for starting game that will display first question and its answers, get next question which displays
// next question and its answers, function for my selected answer
const startButton = document.getElementById("start-btn") //links Variable start button to start-btn button in html
const nextButton = document.getElementById("next-btn") //links Variable start button to start-btn button in html
const questionElementsContainer = document.getElementById("question-Container")  //links this variable to the dev container id which displays question and its answers
const questionElement = document.getElementById("question")
const answerButtonsElement = document.getElementById("answer-buttons")
// 
var cAnswerElement = document.getElementById("correctAnswer")
let wAnswerElement = document.getElementById("worrectAnswer")
let shuffle, currentQuestionsIndex; //undefined 
var cCounter;

startButton.addEventListener("click", startGame)

nextButton.addEventListener("click", () => {
    currentQuestionsIndex++
    // cAnswerElement++
    setNextQuestion()
    // document.getElementById("btn").disabled = false;
})



function startGame() {
    cCounter = 0
    cAnswerElement.innerText=0;
    console.log("GameStarted")

    startButton.classList.add("hide") // hides the button after clicking it
    shuffle = questions.sort(() => Math.random() - 0.5)
    currentQuestionsIndex = 0;
    questionElementsContainer.classList.remove("hide") //unhides question and answers
    setNextQuestion();  // here it will auto put the first question after it started
} //end of startGame function

function setNextQuestion() {
    // setStatusClass(document.body, neutral)
    
    resetState()
    showQuestion(shuffle[currentQuestionsIndex]);
}

function showQuestion(question) {

    questionElement.innerText = question.question

    question.answers.forEach(answer => {
        const button = document.createElement("button")
        button.innerText = answer.text
        button.classList.add("btn")

        if (answer.correct) { //you need to enter correct data
        //   if(answer.correct === true){ cCounter++}
            button.dataset.correct = answer.correct
            // cCounter++
            
        } 
        //  cAnswerElement.innerText= cCounter;
        button.addEventListener('click', selectAnswer)
        
        answerButtonsElement.appendChild(button)

    })

}

//=============================================
function resetState() {
    clearStatusClass(document.body)
    // setStatusClass(document.body, neutral)
    nextButton.classList.add("hide")
    while (answerButtonsElement.firstChild) {
        answerButtonsElement.removeChild(answerButtonsElement.firstChild)
    }
}

//============================================
function selectAnswer(e) {
    const selectedButton = e.target
    const correct = selectedButton.dataset.correct
    setStatusClass(document.body, correct)

    //stack overflow help :D .... I dont understand it fully
    Array.from(answerButtonsElement.children).forEach(button => {
        setStatusClass(button, button.dataset.correct)
        
        //add two buttons with the a appended value from the array
          
    })
    if (shuffle.length > currentQuestionsIndex + 1) {
        nextButton.classList.remove("hide")
        // cAnswerElement.innerText=cAnswerElementt;
        // wAnswerElement.innerText=wAnswerElementt;
    } else {
        startButton.innerText = "Restart The Quiz"
        startButton.classList.remove("hide")
    }

}

function setStatusClass(element, correct) {
    clearStatusClass(element)
    if (correct) {
            cCounter= cCounter+1;
            cAnswerElement.innerText= cCounter;
            //  document.getElementById("btn").disabled = true;          /////////////////////////////////////////////////
        element.classList.add("correct")
        // document.getElementById("btn").disabled = true;
       
    }
    else {
        element.classList.add("wrong")
        cCounter= cCounter-1;
        // document.getElementById("btn").disabled = true;
        // document.getElementById("btn").disabled = true;
    }
}



function clearStatusClass(element) {
    element.classList.remove("correct")
    element.classList.remove("wrong")
}

const questions = [

    {
        question: "What is my name?",
        answers: [
            { text: "Banana", notcorrect: false },
            { text: "Adam", correct: true }
        ]
    },

    {
        question: "What is 2+2?",
        answers: [
            { text: "5", notcorrect: false },
            { text: "4", correct: true }
        ]
    },

    {
        question: "What is the best programming langauge?",
        answers: [
            { text: "JS", notcorrect: false },
            { text: "Java", correct: true }
        ]
    },

    {
        question: "How to copy a line of code in JS?",
        answers: [
            { text: "Ctrl+Alt+Delete", notcorrect: false },
            { text: "Alt + Shift + ArrowKeys", correct: true }
        ]
    },

    {
        question: "Why is CSS so annoying?",
        answers: [
            { text: "Heek", notcorrect: false },
            { text: "It is not!", correct: true }
        ]
    },

    {
        question: "What is my cats name ?",
        answers: [
            { text: "Kitten", notcorrect: false },
            { text: "Jack", correct: true }
        ]
    }
]


// add counter for correct answer
// add counter for wrong answer
// add result
// display above in a nice page where you enter your name
// save in local storage
Dronz
  • 1,970
  • 4
  • 27
  • 50
Adam.M
  • 57
  • 7

1 Answers1

0
  1. All the lines that set the disabled property are commented out with "//".

  2. All the lines that set the disabled property try to load element "btn", but the ID string needs to match the actual element you want to disable, e.g. "start-btn".

  3. To change behavior such as disabling a counter, wrap the code that increments the counter in an if (ShouldCount) { [code that increments here] } condition. Have ShouldCount start true and set it to false when something happens that you want to stop the counter, and true when something happens that you want to restart the counter.

  4. I don't know what you're trying to do with FontAwesome, but you should ask individual questions, not all your questions in one question.

Dronz
  • 1,970
  • 4
  • 27
  • 50
  • 1 Yes i have them disabled because they are screwing my code up 2 All the lines that set the disabled property try to load element "btn", but the ID string needs to match the actual element you want to disable, e.g. "start-btn". Am I using the incorrect class? for the button ? I have them set in html to button class="btn" 3 as for wraping the code for incrementing, do u mean that i need to put in a dedicated if condition ? sorry I am still learning and I dunno if I am expressing my thoughts correctly – Adam.M Aug 01 '21 at 16:55
  • GetElementByID() does NOT target the CSS class in any way - it targets the ID string of the element. – Dronz Aug 01 '21 at 17:13
  • If you mean the code where you currently say "if (correct) { cCounter= cCounter+1;" then you would want to do something such as change it to something like if ((correct) && (shouldCount)) { cCounter= cCounter+1;" and also define shouldCount as true when you set up cCounter = 0; and then also set shouldCount to true or false when handling events that you want to turn the counter on or off. – Dronz Aug 01 '21 at 17:18
  • BTW the reason why those lines "screw your code up" is because they are looking for an element with an ID (not class) of "btn", and there are no elements with that ID, so those calls throw an error to help you find the problem. – Dronz Aug 01 '21 at 17:20
  • Thanks all, I will try to apply what you are telling me and I will get back to you soon :) <3 – Adam.M Aug 01 '21 at 18:39
  • 1
    `function setNextQuestion() { shouldCount=true;.... function setStatusClass(element, correct) { clearStatusClass(element) if (correct) { if(shouldCount===true){ cCounter= cCounter+100; cAnswerElement.innerText= cCounter; } element.classList.add("correct") } else { shouldCount=false; element.classList.add("wrong") } shouldCount=false; }` Thanks Dronz – Adam.M Aug 01 '21 at 22:32