javascript
/**
* Wizard UI Object Model
*
* This JavaScript object model creates and manages a multi-step wizard UI entirely in the DOM.
* Features:
* - Dynamic DOM creation (no pre-existing HTML required).
* - Progress indicator with step titles.
* - Swappable step content (HTML strings or DOM elements).
* - Next/Prev buttons with state management (disabled appropriately).
* - Current step state tracking.
* - Events for step changes (onNext, onPrev, onStepChange).
*
* Usage:
* const wizard = new Wizard(steps);
* document.body.appendChild(wizard.element); // or insert elsewhere
* wizard.next(); // Programmatic navigation
*
* Append to any container: container.appendChild(wizard.element);
*/
class Wizard {
constructor(steps) {
this.steps = steps; // Array of { id: number, title: string, content: string|HTMLElement }
this.currentStep = 0;
this.totalSteps = steps.length;
this.element = null;
this.onStepChange = null; // Callback: (currentStep, prevStep) => {}
this.onNext = null; // Callback before next
this.onPrev = null; // Callback before prev
this.isValidStep = () => true; // Override for validation: (stepIndex) => boolean
this.createDOM();
this.attachEvents();
this.updateUI();
}
createDOM() {
// Root wizard container
this.element = document.createElement('div');
this.element.className = 'wizard-container';
// Progress header
const progress = document.createElement('div');
progress.className = 'wizard-progress';
this.progress = progress;
// Steps container
const stepsContainer = document.createElement('div');
stepsContainer.className = 'wizard-steps';
this.stepsContainer = stepsContainer;
// Navigation footer
const nav = document.createElement('div');
nav.className = 'wizard-nav';
this.nav = nav;
// Prev button
this.prevBtn = document.createElement('button');
this.prevBtn.id = 'wizard-prev';
this.prevBtn.className = 'wizard-btn wizard-prev';
this.prevBtn.textContent = 'Previous';
this.prevBtn.disabled = true;
// Next button
this.nextBtn = document.createElement('button');
this.nextBtn.id = 'wizard-next';
this.nextBtn.className = 'wizard-btn wizard-next';
this.nextBtn.textContent = 'Next';
nav.appendChild(this.prevBtn);
nav.appendChild(this.nextBtn);
// Assemble
this.element.appendChild(progress);
this.element.appendChild(stepsContainer);
this.element.appendChild(nav);
// Pre-render progress and steps
this.renderProgress();
this.renderSteps();
}
renderProgress() {
this.progress.innerHTML = '';
this.steps.forEach((step, index) => {
const stepIndicator = document.createElement('div');
stepIndicator.className = `progress-step ${index === this.currentStep ? 'active' : ''}`;
stepIndicator.innerHTML = `
<div class="step-circle">${index + 1}</div>
<div class="step-title">${step.title}</div>
`;
this.progress.appendChild(stepIndicator);
});
}
renderSteps() {
this.stepsContainer.innerHTML = '';
this.steps.forEach(step => {
const stepEl = document.createElement('div');
stepEl.className = 'wizard-step';
stepEl.dataset.step = step.id;
stepEl.style.display = 'none'; // Hidden by default
if (typeof step.content === 'string') {
stepEl.innerHTML = step.content;
} else {
stepEl.appendChild(step.content);
}
this.stepsContainer.appendChild(stepEl);
});
}
attachEvents() {
this.prevBtn.addEventListener('click', () => this.prev());
this.nextBtn.addEventListener('click', () => this.next());
}
updateUI() {
// Update progress
this.renderProgress();
// Show current step
Array.from(this.stepsContainer.children).forEach((stepEl, index) => {
stepEl.style.display = index === this.currentStep ? 'block' : 'none';
});
// Update buttons
this.prevBtn.disabled = this.currentStep === 0;
this.nextBtn.disabled = this.currentStep === this.totalSteps - 1 && !this.isValidStep(this.currentStep);
this.nextBtn.textContent = this.currentStep === this.totalSteps - 1 ? 'Finish' : 'Next';
// Trigger callback
if (this.onStepChange) {
this.onStepChange(this.currentStep, this.currentStep - 1);
}
}
next() {
if (this.onNext) this.onNext(this.currentStep);
if (this.currentStep < this.totalSteps - 1 && this.isValidStep(this.currentStep)) {
this.currentStep++;
this.updateUI();
}
}
prev() {
if (this.onPrev) this.onPrev(this.currentStep);
if (this.currentStep > 0) {
this.currentStep--;
this.updateUI();
}
}
goTo(stepIndex) {
if (stepIndex >= 0 && stepIndex < this.totalSteps) {
this.currentStep = stepIndex;
this.updateUI();
}
}
getCurrentStepData() {
return this.steps[this.currentStep];
}
// Example CSS for styling (inject via style tag or external)
getCSS() {
return `
.wizard-container {
max-width: 600px;
margin: 20px auto;
font-family: Arial, sans-serif;
border: 1px solid #ddd;
border-radius: 8px;
overflow: hidden;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
.wizard-progress {
display: flex;
background: #f8f9fa;
border-bottom: 1px solid #ddd;
}
.progress-step {
flex: 1;
text-align: center;
padding: 15px 10px;
position: relative;
}
.progress-step:not(:last-child)::after {
content: '';
position: absolute;
top: 25px;
left: 50%;
right: 0;
height: 2px;
background: #e9ecef;
z-index: -1;
}
.progress-step.active::after { background: #007bff; }
.step-circle {
width: 30px;
height: 30px;
border-radius: 50%;
background: #e9ecef;
margin: 0 auto 5px;
display: flex;
align-items: center;
justify-content: center;
font-weight: bold;
color: #6c757d;
}
.progress-step.active .step-circle {
background: #007bff;
color: white;
}
.step-title {
font-size: 12px;
font-weight: bold;
color: #6c757d;
}
.progress-step.active .step-title { color: #007bff; }
.wizard-steps {
min-height: 300px;
padding: 30px;
}
.wizard-step {
animation: fadeIn 0.3s ease-in;
}
@keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
.wizard-nav {
display: flex;
justify-content: space-between;
padding: 20px 30px;
background: white;
border-top: 1px solid #ddd;
}
.wizard-btn {
padding: 10px 20px;
border: 1px solid #007bff;
background: #007bff;
color: white;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
}
.wizard-btn:hover:not(:disabled) { background: #0056b3; }
.wizard-btn:disabled { background: #6c757d; border-color: #6c757d; cursor: not-allowed; }
.wizard-prev { background: #6c757d; border-color: #6c757d; }
.wizard-prev:hover:not(:disabled) { background: #545b62; }
`;
}
}
// Example usage:
const exampleSteps = [
{
id: 0,
title: 'Personal Information',
content: `
<h3>Step 1: Personal Info</h3>
<div>
<label>Name: <input type="text" id="name" style="width:100%; padding:8px; margin:5px 0;"></label>
</div>
`
},
{
id: 1,
title: 'Address',
content: `
<h3>Step 2: Address</h3>
<div>
<label>Street: <input type="text" id="street" style="width:100%; padding:8px; margin:5px 0;"></label>
<label>City: <input type="text" id="city" style="width:100%; padding:8px; margin:5px 0;"></label>
</div>
`
},
{
id: 2,
title: 'Confirmation',
content: `
<h3>Step 3: Review & Submit</h3>
<p>Check your info and submit!</p>
<div style="background:#f8f9fa; padding:15px; border-radius:4px;">
Name: <span id="review-name">-</span><br>
Street: <span id="review-street">-</span>
</div>
`
}
];
// Initialize
const wizard = new Wizard(exampleSteps);
// Optional: Inject CSS
const style = document.createElement('style');
style.textContent = wizard.getCSS();
document.head.appendChild(style);
// Append to body (or any container)
document.body.appendChild(wizard.element);
// Demo: Custom validation and callbacks
wizard.isValidStep = (stepIndex) => {
if (stepIndex === 0) return !!document.getElementById('name')?.value.trim();
if (stepIndex === 1) return !!document.getElementById('street')?.value.trim();
return true;
};
wizard.onNext = (step) => {
if (step === 2) {
// Update review
document.getElementById('review-name').textContent = document.getElementById('name').value;
document.getElementById('review-street').textContent = document.getElementById('street').value;
}
};
// Programmatic navigation example (e.g., after 2s)
// setTimeout(() => wizard.next(), 2000);