In Reveal.js, fragments are stepped through one at a time, and you can access the current fragment index using the Reveal.js API.
To display the current fragment index on the slide, you can use JavaScript to listen for fragment changes and update a DOM element accordingly.
✅ Step-by-step solution:
1. Add a placeholder in your HTML (e.g., in your slide):
html
<section>
<h2>Fragment Counter</h2>
<p class="fragment">First fragment</p>
<p class="fragment">Second fragment</p>
<p class="fragment">Third fragment</p>
<!-- This will show the current fragment index -->
<div id="fragment-counter" style="position: fixed; bottom: 10px; right: 10px; background: rgba(0,0,0,0.5); color: white; padding: 5px 10px; border-radius: 5px;">
Fragment: <span id="current-fragment">0</span> / <span id="total-fragments">0</span>
</div>
</section>
2. Add JavaScript to update the counter:
You can add this in your index.html or in a separate JS file loaded after Reveal.js:
html
<script>
function updateFragmentCounter() {
const current = Reveal.getIndices().f || 0;
const total = Reveal.getCurrentSlide().querySelectorAll('.fragment').length;
document.getElementById('current-fragment').textContent = current;
document.getElementById('total-fragments').textContent = total;
}
// Update on fragment change
Reveal.addEventListener('fragmentshown', updateFragmentCounter);
Reveal.addEventListener('fragmenthidden', updateFragmentCounter);
// Also update on slide change
Reveal.addEventListener('slidechanged', updateFragmentCounter);
</script>
✅ Result
As you navigate through fragments, the counter will update in real time, showing something like:
code
Fragment: 2 / 3
🔁 Optional: Hide when no fragments
You can hide the counter entirely if the slide has no fragments:
js
function updateFragmentCounter() {
const current = Reveal.getIndices().f || 0;
const fragments = Reveal.getCurrentSlide().querySelectorAll('.fragment');
const total = fragments.length;
const counter = document.getElementById('fragment-counter');
if (total === 0) {
counter.style.display = 'none';
} else {
counter.style.display = 'block';
document.getElementById('current-fragment').textContent = current;
document.getElementById('total-fragments').textContent = total;
}
}
Let me know if you want this styled as a Reveal.js plugin or integrated into the speaker notes view.