Skip to content

Instantly share code, notes, and snippets.

@dorinvancea
Last active February 21, 2023 09:02
Show Gist options
  • Save dorinvancea/99bf049e4fb401b31b6d12c05aa902b3 to your computer and use it in GitHub Desktop.
Save dorinvancea/99bf049e4fb401b31b6d12c05aa902b3 to your computer and use it in GitHub Desktop.
Ruby on Rails Stimulus: Simple carousel flow
.onboarding-step {
display: none;
}
.onboarding-step.active {
display: block;
}
// app/javascript/controllers/onboarding_controller.js
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static targets = ['step'];
static classes = [ 'active' ]
connect() {
this.showStep(0);
}
next() {
if (this.currentStep < this.stepTargets.length - 1) {
this.showStep(this.currentStep + 1);
}
}
previous() {
if (this.currentStep > 0) {
this.showStep(this.currentStep - 1);
}
}
showStep(step) {
this.stepTargets.forEach((stepTarget) => {
stepTarget.classList.remove(this.activeClass);
});
this.stepTargets[step].classList.add(this.activeClass);
this.currentStep = step;
}
get currentStep() {
return parseInt(this.data.get('currentStep'));
}
set currentStep(value) {
this.data.set('currentStep', value);
}
}
<h1>Onboarding</h1>
<div id="onboarding-steps" data-controller="onboarding" data-onboarding-active-class="active">
<div class="onboarding-step" data-onboarding-target="step" data-current-step="1">
<h3>Step 1</h3>
</div>
<div class="onboarding-step" data-onboarding-target="step" data-current-step="2" >
<h3>Step 2</h3>
</div>
<div class="onboarding-step" data-onboarding-target="step" data-current-step="3">
<h3>Step 3</h3>
</div>
<div>
<button href="" data-action="click->onboarding#previous:prevent">Previous</button>
<button href="" data-action="click->onboarding#next:prevent">Next</button>
</div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment