Guide 3.5: Real Projects
Build the Question Interface
Now that our global state array is populated with 40 questions, we need to build the UI that will display the current question, the four multiple-choice options, and radio buttons for the user to make a selection.
The Exam Screen HTML
3.5.1Go back to your index.html file. Right below the #homeScreen div, add this new markup for the exam interface.
<div id="examScreen" class="screen">
<div class="exam-header">
<h2 id="displaySubject">Subject</h2>
<div class="timer" id="timerDisplay">00:00</div>
</div>
<div class="question-container">
<div class="question-meta">
<span>Question <span id="qNumber">1</span> of 40</span>
</div>
<!-- Optional image rendering -->
<img id="qImage" src="" style="display: none; max-width: 100%;">
<!-- The actual question text -->
<p id="qText" class="question-text">Loading question...</p>
<!-- Radio button options -->
<div class="options-group" id="optionsContainer">
<!-- Options will be injected here by JS -->
</div>
</div>
<!-- Navigation buttons (We will implement logic for these later) -->
<div class="exam-footer">
<button id="prevBtn">Previous</button>
<button id="nextBtn">Next</button>
</div>
</div>The Render Function
3.5.2Open app.js and let's define the renderQuestion(index) function we called in the last step. This function pulls data from the global array and injects it into the DOM.
function renderQuestion(index) {
const qData = examQuestions[index];
// Update header and meta info
document.getElementById('displaySubject').textContent = subjectSelect.options[subjectSelect.selectedIndex].text;
document.getElementById('qNumber').textContent = index + 1;
// Render question text
document.getElementById('qText').textContent = qData.question;
// Handle optional images
const imgEl = document.getElementById('qImage');
if (qData.image) {
imgEl.src = qData.image;
imgEl.style.display = 'block';
} else {
imgEl.style.display = 'none';
}
// Generate options
const optionsContainer = document.getElementById('optionsContainer');
optionsContainer.innerHTML = ''; // Clear previous options
// Loop through keys: 'a', 'b', 'c', 'd'
for (const [key, text] of Object.entries(qData.option)) {
if (!text) continue; // Skip empty options
const wrapper = document.createElement('div');
wrapper.className = 'option-wrapper';
const input = document.createElement('input');
input.type = 'radio';
input.name = 'exam_option';
input.value = key;
input.id = `opt_${key}`;
// If user previously selected this option, keep it checked!
if (userAnswers[index] === key) {
input.checked = true;
}
const label = document.createElement('label');
label.htmlFor = `opt_${key}`;
label.textContent = `${key.toUpperCase()}. ${text}`;
wrapper.appendChild(input);
wrapper.appendChild(label);
optionsContainer.appendChild(wrapper);
}
}