Randomize slides in reveal.js

While Reveal itself does not have this functionality built in, it does let you set up event hooks to do actions when all the slides are loaded, this means JQUERY TO THE RESCUE!

You can combine Reveal’s “All slides are ready” event with simple javascript to reorder all the sections, here’s a simple PoC:

First import jQuery, I did this by adding it directly above the import for js/reveal.min.js:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Then, set up an event listener:

Reveal.addEventListener('ready', function(event) {
    // Declare a function to randomize a jQuery list of elements
    // see http://stackoverflow.com/a/11766418/472021 for details           
    $.fn.randomize = function(selector){
        (selector ? this.find(selector) : this).parent().each(function(){
            $(this).children(selector).sort(function(){
                return Math.random() - 0.5;
            }).detach().appendTo(this);
        });

        return this;
    };

    // call our new method on all sections inside of the main slides element.
    $(".slides > section").randomize();
});

I put this right after declaring my Reveal settings and dependencies, but I’m pretty sure you can put it anywhere.

What this does is waits for all javascript, css, etc to load, manually reorders the slides in the DOM, then lets Reveal start off doing its thing. You should be able to combine this with all your other reveal settings since it’s not doing anything disruptive to reveal itself.

Regarding the “shuffling them each time around” portion, the easiest way to do this would be to use another event listener, slidechanged. You could use this listener to check if the last slide has just been transitioned to, after which the next time slidechanged is called you could simply refresh the page.

You can do this with something like:

var wasLastPageHit = false;
Reveal.addEventListener('slidechanged', function(event) {           
    if (wasLastPageHit) {
        window.location.reload();
    }       

    if($(event.currentSlide).is(":last-child")) {
        // The newly opened slide is the last one, set up a marker
        // so the next time this method is called we can refresh.
        wasLastPageHit = true;
    }
});

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)