execute function when certain slide appear in reveal.js
Asked Answered
M

2

16

I create a presentation with this javascript framework http://lab.hakim.se/reveal-js/#/ and when certain slide is appearing I want to execute function stats(), which display some data from API every 5 seconds, but only when this slide is appearing

function stats(){                
$.ajax({
    type: "GET",
    url: url_survey,
    dataType: "json",
    success : 
      function (data) {
      //some code to display data       
    },
    error:
      //some code
}); 
}

in HTML file I have this:

<section>
<div id="stats">
</div>
</section>

how can I do it? I wrote this code, but it works always, not only when slide appear

function check(){
if($("#stats").is(":visible"))
stats();
}

check();
setInterval(function(){check()}, 2000);
Myron answered 2/3, 2014 at 21:29 Comment(0)
F
23

This can be achieved by using reveal.js states (https://github.com/hakimel/reveal.js#states).

1) Add a unique state to the section that should trigger your method.

<section data-state="stats">
    <h2>This will trigger a state event with the name "stats".</h2>
</section>

2) Add a listener to your custom state using the reveal.js API.

Reveal.addEventListener( 'stats', function() {
    // Called each time the slide with the "stats" state is made visible
} );

Complete working example: https://gist.github.com/hakimel/cea4305a33713d4a5a7e

Funchal answered 8/5, 2014 at 10:39 Comment(3)
yes, but I need have in HTML this: <section><div id="stats"></div></section> ... is there some other solution how to make it in external js file @FunchalMyron
Cool, is it possible to pass arguments to the event handler function? ThanksNothing
@Nothing I'm not sure if it's the best solution, but using datasets you can add in your slide something like data-your-data="42" and then inside your callback function you can access it using Reveal.getCurrentSlide().dataset.pluginPage.Chaunceychaunt
T
1

To answer Philippe Leefsma's question: you can use bind() to pass arguments, like so:

drawDiagramOnSlide.bind(
    null,
    slideName,
    slideEl.querySelector('.diagram')
));

Assuming drawDiagramOnSlide looks like this:

function drawDiagramOnSlide(_slideName, _diagramEl, _event) {...}

The bind call will create a function that calls drawDiagramOnSlide with the correct slide name and element (in my case, a div with class diagram inside the slide ).

Timberwork answered 11/7, 2016 at 11:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.