1. Understand the Goal: The user wants a JavaScript object model (DOM structure) for a "Wizard UI". This implies a multi-step form or process. Key requirements are "next/prev buttons" and "managing current step state".
-
Identify the Core Components:
- The Wizard Container: The main wrapper.
- Steps (Pages): Individual sections of content.
- Navigation Controls: Next, Previous, and maybe Finish/Cancel buttons.
- State Management: Need to track the current step, total steps, and validity of steps.
-
Determine the Approach:
- I shouldn't just write HTML. The prompt asks for a JavaScript object model and DOM structure. This suggests I should show how to represent the UI in JS objects and how that maps to the actual DOM elements, or how to create a class/structure that manages both.
- I'll create a class-based approach (ES6) as it's the standard for managing state and behavior in modern JS without frameworks (vanilla JS).
- I need to show the HTML structure for context, then the JS logic.
-
Drafting the HTML Structure (Mental or Scratchpad):
div.wizard
div.wizard-header (Optional, but good for steps indicator)
div.wizard-content
div.step (active)
div.step
div.wizard-nav
-
Drafting the JavaScript Object Model:
- I need a
Wizard class.
- Properties:
currentStep: Integer (0-indexed or 1-indexed? 0-indexed is better for arrays).
totalSteps: Integer.
steps: Array of DOM elements or configuration objects.
domReferences: Object holding references to the container, buttons, etc.
- Methods:
init(): Setup event listeners.
goToNext(): Validate and increment.
goToPrev(): Decrement.
updateUI(): Hide/show steps, update buttons.
validateStep(): Check if data is okay (mock implementation).
-
Refining the "State Management":
- Simply tracking an integer isn't enough. What about visited history? Validation status?
- Let's keep it relatively simple but extensible. The state should hold
currentStepIndex.
- Self-Correction: The prompt specifically asks for the Object Model (DOM structure). I should provide a configuration object that defines the structure and a Class that manipulates it.
-
Developing the Solution - Step-by-Step:
-
Step 1: The HTML. Keep it semantic and accessible. Use role="tabpanel" etc., or just simple classes for clarity. Let's stick to simple classes for the example but mention accessibility.
-
Step 2: The JavaScript Class (The Core).
- Constructor accepts a config object (selectors).
- State variable:
_currentStep.
- Event listeners on buttons.
-
Step 3: The Logic for State Transitions.
next: If current < max, increment, render.
prev: If current > 0, decrement, render.
- Rendering logic: Loop through steps, toggle
.active class. Toggle disabled on buttons.
-
Adding "Object Model" Context:
-
Sometimes "Object Model" implies a JSON representation of the UI. I will include a "State Object" structure to visualize the data management separately from the DOM manipulation.
-
State Object Example:
const wizardState = {
currentStep: 0,
steps: [
{ id: 'step-1', visited: false, completed: false },
{ id: 'step-2', visited: false, completed: false }
]
}
-
Structuring the Final Output:
- Part 1: HTML Structure: The skeleton.
- Part 2: The JavaScript Class: The logic engine.
- Part 3: State Management Details: How to handle the data.
- Part 4: CSS (Minimal): To make it actually work (hiding/showing).
-
Refining the Code (Self-Correction during drafting):
- Issue: Hardcoding selectors makes it rigid.
- Fix: Pass selectors into the constructor.
- Issue: Accessibility (A11y).
- Fix: Mention
aria-hidden and aria-current in the JS logic.
-
Final Polish:
- Ensure the "Next" button turns to "Submit" on the last step.
- Ensure "Prev" is hidden on the first step.
- Comment the code well.
-
Generating the Output: (This matches the provided good response, focusing on a Vanilla JS implementation of the "Revealing Module Pattern" or a standard Class).
-
Review against prompt:
- "JavaScript object model": Check.
- "DOM structure": Check.
- "Next/Prev buttons": Check.
- "Manage current step state": Check.
-
Formatting: Use code blocks, bold text for emphasis, and clear headings. (Proceed to generate output).
Here is a robust architecture for a Wizard UI. This solution separates the State (data) from the DOM (view) and uses a Controller class to bridge them.
1. The HTML Structure (The View)
First, we need a semantic DOM structure. We will use data attributes to identify steps and navigation buttons.
<div id="wizard-container" class="wizard-wrapper">
<!-- Progress Header (Optional) -->
<div class="wizard-header">
<div class="progress-bar"><div class="progress-fill"></div></div>
</div>
<!-- The Steps Container -->
<div class="wizard-content">
<!-- Step 1 -->
<div class="wizard-step" data-step-id="1">
<h3>Step 1: Personal Details</h3>
<input type="text" placeholder="Name" />
</div>
<!-- Step 2 -->
<div class="wizard-step" data-step-id="2">
<h3>Step 2: Preferences</h3>
<select><option>Option A</option></select>
</div>
<!-- Step 3 -->
<div class="wizard-step" data-step-id="3">
<h3>Step 3: Confirmation</h3>
<p>Are you sure?</p>
</div>
</div>
<!-- Navigation Controls -->
<div class="wizard-nav">
<button class="btn-prev" disabled>Previous</button>
<button class="btn-next">Next</button>
</div>
</div>
2. The JavaScript Object Model
We will create a WizardManager class. This object handles the state (current step), caches DOM references for performance, and binds events.
The Logic
- State Object: Stores the current index and the total number of steps.
- DOM Cache: Queries the DOM once during initialization.
- Navigation Logic: Calculates
min/max boundaries to prevent going out of bounds.
- Render Method: Updates the UI based on the state (adds/removes classes, disables buttons).
class WizardManager {
constructor(containerSelector) {
// 1. Initialize State
this.state = {
currentStep: 0,
totalSteps: 0,
isSubmitting: false
};
// 2. Cache DOM Elements
this.container = document.querySelector(containerSelector);
if (!this.container) return console.error("Wizard container not found");
this.steps = Array.from(this.container.querySelectorAll('.wizard-step'));
this.btnPrev = this.container.querySelector('.btn-prev');
this.btnNext = this.container.querySelector('.btn-next');
// 3. Setup Initial State Data
this.state.totalSteps = this.steps.length;
// 4. Bind Events
this.btnPrev.addEventListener('click', () => this.goToPrevStep());
this.btnNext.addEventListener('click', () => this.handleNextClick());
// 5. Initial Render
this.render();
}
// --- State Management Methods ---
goToPrevStep() {
if (this.state.currentStep > 0) {
this.state.currentStep--;
this.render();
}
}
goToNextStep() {
// Only proceed if validation passes (pseudo-code)
if (this.validateCurrentStep()) {
if (this.state.currentStep < this.state.totalSteps - 1) {
this.state.currentStep++;
this.render();
} else {
this.finishWizard();
}
}
}
handleNextClick() {
// If we are on the last step, the "Next" button acts as "Submit"
if (this.state.currentStep === this.state.totalSteps - 1) {
this.finishWizard();
} else {
this.goToNextStep();
}
}
// --- Logic & Validation ---
validateCurrentStep() {
const currentStepElement = this.steps[this.state.currentStep];
// Example: check if inputs are valid
const inputs = currentStepElement.querySelectorAll('input, select, textarea');
let isValid = true;
inputs.forEach(input => {
if (!input.checkValidity()) {
isValid = false;
// You would highlight errors here
}
});
return isValid;
}
finishWizard() {
console.log("Wizard Complete! Submitting data...");
this.btnNext.disabled = true;
this.btnNext.textContent = "Submitting...";
// API calls go here
}
// --- Render / UI Update ---
render() {
const { currentStep, totalSteps } = this.state;
// 1. Update Step Visibility
this.steps.forEach((step, index) => {
step.classList.remove('active'); // CSS hides elements without .active
if (index === currentStep) {
step.classList.add('active');
}
});
// 2. Update "Previous" Button State
if (currentStep === 0) {
this.btnPrev.disabled = true;
} else {
this.btnPrev.disabled = false;
}
// 3. Update "Next" Button Text (Next vs Submit)
if (currentStep === totalSteps - 1) {
this.btnNext.textContent = "Submit";
} else {
this.btnNext.textContent = "Next";
}
}
}
// Initialize the Wizard
document.addEventListener('DOMContentLoaded', () => {
const myWizard = new WizardManager('#wizard-container');
});
3. CSS Styling (The Glue)
This CSS ensures only the active step is visible and handles transitions.
.wizard-wrapper {
border: 1px solid #ddd;
padding: 20px;
max-width: 600px;
margin: 0 auto;
border-radius: 8px;
}
/* Hide all steps by default */
.wizard-step {
display: none;
opacity: 0;
transition: opacity 0.3s ease;
min-height: 200px; /* Prevent layout jump */
}
/* Show only the active step */
.wizard-step.active {
display: block;
opacity: 1;
}
.wizard-nav {
margin-top: 20px;
display: flex;
justify-content: space-between;
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
Key Concepts in this Implementation
- Single Source of Truth: The
this.state object dictates what the user sees. We never manually hide/show DOM elements outside of the render() function. We simply update this.state.currentStep and call render().
- Array Conversion:
Array.from(this.container.querySelectorAll(...)) is crucial. It allows us to use array methods like .forEach and access elements by index easily (this.steps[index]).
- Boundary Checks: The logic prevents
currentStep from going below 0 or above totalSteps - 1.
- Dynamic Button Role: The "Next" button text changes to "Submit" automatically based on the state, improving User Experience (UX).