Let’s create a mini quiz

JavaScript

0 Comments

In this section, you'll see how to create a quiz question that will be checked using only JavaScript. Some of the JavaScript you've seen before, but we'll also be covering some new topics.

New topics we'll be covering:

  • Preventing the default action from happening for an event
  • Getting and setting HTML attribute values
  • Creating custom HTML attributes
  • Changing the HTML inside an element

Working example for our quiz question

Try it yourself to see how it works. When you enter the right answer it will say "Correct", and when the wrong answer is entered, you'll see "Incorrect".

Below, you'll see the HTML and JavaScript code for this quiz. We'll explain the code more in the following sections.

HTML

<style>
    .correct,
    .incorrect {
        font-weight: bold;
    }

    .correct {
        color: green;
    }

    .incorrect  {
        color: red;
    }

    /* Keep the result hidden until we're ready */
    .result {
        display: none;
    }
</style>

<form id="quizQuestion">
    <p>
        What JavaScript event is fired when the page is fully loaded?
    </p>

    <input type="text" name="answer">

    <input type="submit" value="Submit" data-answer="load">

    <p class="result"></p>
</form>

Notice that, on Line 28, we save the correct answer as an attribute of the submit button (in the data-answer attribute). We'll come back and make this more secure in a later exercise.

JavaScript

function setupQuiz() {
    var quizForm = document.querySelector('#quizQuestion');

    quizForm.addEventListener('submit', checkAnswer);
}

function checkAnswer(event) {
    // Don't submit the form to the server
    event.preventDefault();

    var quizForm = document.querySelector('#quizQuestion');
    // Search inside quizForm (not the whole document)
    var result = quizForm.querySelector('.result');

    var answerBox = quizForm.querySelector('input[name="answer"]');
    var userAnswer = answerBox.value;

    var submitButton = quizForm.querySelector('input[type="submit"]');
    var correctAnswer = submitButton.getAttribute('data-answer');

    if (userAnswer == correctAnswer) {
        result.innerHTML = '<span class="correct">Correct</span>';
    } else {
        result.innerHTML = '<span class="incorrect">Incorrect</span>';
    }

    // Make the result visible
    result.style.display = "block";
}

setupQuiz();

event.preventDefault()

function checkAnswer(event) {
    // Don't submit the form to the server
    event.preventDefault();

Notice that we gave the checkAnswer function 1 parameter called event.

Whenever you use addEventListener to create an event handler, you'll be passed an event object that contains information about the event and some functions for managing it.

By default, when the submit button is pressed in a form, the form is submitted to the server. We're handling this form entirely through JavaScript, so we don't want that. event.preventDefault(); stops the default action from happening.

preventDefault is also commonly used when handling the click event on a link to stop the link from opening a new page.

Getting the value entered in an input box

var answerBox = quizForm.querySelector('input[name="answer"]');
var userAnswer = answerBox.value;

Here we used .value to get the current value of the input box.

This syntax also works for most common HTML attributes

For example, .href will get the href attribute on links, and .src will get the src attribute for images. The main exception is .className, which is used to get the value of the class attribute.

Use getAttribute to get any attribute's value

var correctAnswer = submitButton.getAttribute('data-answer');

Another more foolproof way to get the value of any HTML attribute is to use the getAttribute function (as shown above). Why is it more foolproof? Well, it will also work on custom attributes that we make up. And you don't have to worry about exceptions like .className (which can also be accessed with getAttribute('class')).

In this example, we use getAttribute to get the value of the data-answer attribute that we we added to the submit button. This is where we stored the correct answer for the quiz question.

Use setAttribute to create or change an attribute's value

submitButton.setAttribute(attributeName, attributeValue);

Custom HTML attribute names MUST start with "data-"

<input type="submit" value="Submit" data-answer="load">

HTML gives you a way to create your own custom attributes (which is nice for situations just like this). The only requirement is that the attribute name MUST start with "data-". If you don't do this, your HTML will not be valid.

innerHTML - Getting or changing the HTML inside an element

<p class="result"></p>

<script>
    var result = document.querySelector('.result');

    result.innerHTML = '<span class="correct">Correct</span>';
</script>

In this example, we changed the HTML inside the paragraph to show the result.

Here's what the DOM looks like at this point:

<p class="result">
    <span class="correct">Correct</span>
</p>

Leave a Comment