Analyzing Wizard Structure
I'm currently focused on the Wizard UI structure. I'm exploring various DOM structures to represent the steps and transitions, aiming for semantic clarity. The goal is to create a JavaScript object model mirroring the DOM. I'm also considering initial state management frameworks to make it easier to add new features later.
Designing DOM Structure
My current focus is crafting a semantic and accessible DOM structure. I've drafted HTML using <divs>, <ol> and <buttons> for the wizard container, progress indicator (an ordered list), content area, individual steps, and controls. The aim is to make it easy to manipulate with JavaScript and prepare for state management.
Refining Class Wizard
I'm now zeroing in on the Wizard class structure. Its constructor will handle DOM element selection and option parsing. Essential state includes currentStep for tracking progress. The methods will drive the UI. I've designed init() for listeners, showStep(index) for displaying steps and toggling classes, and next() and prev() for navigation.
Defining Step State
I've been figuring out how to manage step state. An array index (0-based) for currentStep seems best. I'm using CSS classes for UI updates. The active class handles visibility, and disabled disables buttons. I've designed logic to restrict navigation using these boundaries.
Coding the Wizard
My approach to coding the wizard leverages CSS display: none by default and applying display: block with .active via JavaScript. Within JavaScript, I'm grabbing all steps, adding click event listeners, and ensuring the currentStep index stays within bounds.
Incorporating Validation Logic
I'm now integrating validation logic into the next() method. I'm adding a hook or placeholder for validation checks before proceeding to the next step, ensuring data integrity. I'll need to define how to handle validation failures and provide user feedback.
Finalizing Navigation Methods
I'm currently finalizing the navigation methods, next() and prev(). I've added error handling to prevent navigation outside of the defined step boundaries, ensuring a smooth and predictable user experience. I'm focusing on their responsibilities for state management, UI updates, and potential validation hooks. I also refined the logic to handle the initial state.
Here is a complete breakdown of a Wizard UI. I have broken this down into the Mental Model (how to structure it logically), the DOM Structure (HTML), and the Logic Class (JavaScript) to manage the state.
1. The Mental Model (State Object)
Before touching the DOM, it helps to visualize the JS object that manages the state. We want to separate the State (data) from the UI (DOM).
const wizardState = {
// Configuration
totalSteps: 4,
// Observable State
currentStepIndex: 0, // 0-based index
// Derived State (calculated based on currentStepIndex)
isFirstStep: true, // currentStepIndex === 0
isLastStep: false, // currentStepIndex === totalSteps - 1
// Data Handling (optional)
formData: {}
};
2. The DOM Structure (HTML)
This structure relies on data attributes and modular containers to make traversing the DOM easy for JavaScript.
<div id="wizard-component" class="wizard">
<!-- 1. Progress Indicator (Optional) -->
<div class="wizard-progress">
<div class="progress-step active">1</div>
<div class="progress-step">2</div>
<div class="progress-step">3</div>
</div>
<!-- 2. Steps Container -->
<div class="wizard-content">
<!-- Step 1 -->
<div class="step active" data-index="0">
<h2>Step 1: Account Info</h2>
<input type="text" name="username" placeholder="Username" required>
</div>
<!-- Step 2 -->
<div class="step hidden" data-index="1">
<h2>Step 2: Personal Details</h2>
<input type="text" name="fullname" placeholder="Full Name">
</div>
<!-- Step 3 -->
<div class="step hidden" data-index="2">
<h2>Step 3: Review</h2>
<p>Review your details...</p>
</div>
</div>
<!-- 3. Controls -->
<div class="wizard-footer">
<button id="btn-prev" disabled>Previous</button>
<button id="btn-next">Next</button>
</div>
</div>
CSS to make it work:
.step.hidden {
display: none;
}
.step.active {
display: block;
animation: fade-in 0.3s;
}
3. The JavaScript Object Model (Class)
Here is a modern ES6 Class implementation. It handles bounds checking, DOM updates, and accessibility states.
class Wizard {
constructor(elementSelector) {
// 1. Select DOM Elements
this.container = document.querySelector(elementSelector);
if (!this.container) throw new Error('Wizard container not found');
this.steps = Array.from(this.container.querySelectorAll('.step'));
this.progressPoints = Array.from(this.container.querySelectorAll('.progress-step'));
this.prevBtn = this.container.querySelector('#btn-prev');
this.nextBtn = this.container.querySelector('#btn-next');
// 2. Initialize State
this.state = {
currentIndex: 0,
total: this.steps.length
};
// 3. Bind Events
this.init();
}
init() {
// Bind Context
this.prevBtn.addEventListener('click', () => this.prev());
this.nextBtn.addEventListener('click', () => this.next());
// Initial UI Paint
this.updateUI();
}
// --- LOGIC & STATE MANAGEMENT ---
next() {
// Optional: Add Validation Logic here
if (!this.validateStep(this.state.currentIndex)) return;
if (this.state.currentIndex < this.state.total - 1) {
this.state.currentIndex++;
this.updateUI();
} else {
this.submit();
}
}
prev() {
if (this.state.currentIndex > 0) {
this.state.currentIndex--;
this.updateUI();
}
}
// --- DOM MANIPULATION ---
updateUI() {
const { currentIndex, total } = this.state;
// 1. Update Step Visibility
this.steps.forEach((step, index) => {
if (index === currentIndex) {
step.classList.remove('hidden');
step.classList.add('active');
} else {
step.classList.add('hidden');
step.classList.remove('active');
}
});
// 2. Update Progress Indicators
this.progressPoints.forEach((point, index) => {
if (index === currentIndex) point.classList.add('active');
else if (index > currentIndex) point.classList.remove('active');
// Note: We usually keep previous steps 'active' to show progress trail
});
// 3. Update Buttons States
// Disable Prev button on first step
this.prevBtn.disabled = currentIndex === 0;
// Change Next button text on last step
if (currentIndex === total - 1) {
this.nextBtn.textContent = 'Finish';
} else {
this.nextBtn.textContent = 'Next';
}
}
// --- UTILITIES ---
validateStep(index) {
const currentStepEl = this.steps[index];
const inputs = currentStepEl.querySelectorAll('input, select, textarea');
let isValid = true;
inputs.forEach(input => {
if (!input.checkValidity()) {
isValid = false;
input.reportValidity(); // Shows browser native error bubble
}
});
return isValid;
}
submit() {
console.log('Wizard Completed. Submitting form...');
// logic to submit form data
alert("Wizard Finished!");
}
}
// --- INSTANTIATION ---
document.addEventListener('DOMContentLoaded', () => {
const myWizard = new Wizard('#wizard-component');
});
Key Implementation Patterns Used:
- Array-Based State: We treat the steps as an array. Moving
Next adds +1 to the index, moving Prev adds -1. This makes it O(1) efficient to find the current step.
- Single Source of Truth: The
this.state.currentIndex variable is the only thing that determines what the UI looks like. We do not check the DOM to see "which class has active". We update the state efficiently, then repaint the DOM based on that state.
- Bound Guards: In
next() and prev(), we check if (index > 0) or if (index < total) to prevent errors.
- Validation Hook: The
validateStep method runs before state transitions. This prevents the user from moving to index 1 if index 0 has invalid inputs.