What is the canonical way of adding JavaScript to a `xaringan` presentation?

I'm trying to add JavaScript to a xaringan document, and none of the standard mechanisms seem to work.

For example, using a {js} chunk doesn't work.

```{js}
alert("made it here");
```

Neither does a <script> tag:

<script>
alert("made it here");
<script>

In both cases xaringan seems to simply insert the JavaScript as text, and I never get the alert.

A kludgy workaround

In the end I found a mechanism that works, based on the rmarkdown::includes() function. This works by creating an html file that contains the script, and then inserting it via the xaringan yaml header.

This is my toc.html:

<script>
alert("made it here");
</script>

And then I insert it in my yaml header like this:

output:  
  xaringan::moon_reader:
    includes:
      in_header:
        - 'toc.html'

There has to be a better way. Can you help me find it?

Not sure if it is better, but you can save your script in a file - consider macros.js - and have it executed from nature:beforeInit: section of your front matter

output:
  xaringan::moon_reader:
    css: ["default", "./libs/JLA-fonts.css"]
    lib_dir: libs
    nature:
      highlightStyle: github
      highlightLines: true
      countIncrementalSlides: false
      ratio: "16:9"
      beforeInit: "./libs/macros.js"
2 Likes

That's what I'd do, too.

However, I suggest you use a different folder. The libs/ folder was specified by the lib_dir, and it will be automatically generated to include other JS/CSS files, which means this folder could be automatically removed, so you'd better not put anything manually created in this folder.

BTW, @andrie's motivating use case was https://github.com/yihui/xaringan/issues/217. The beforeInit option may not work in that case because the JS code is executed before remark.js initializes the slides from Markdown to HTML. In other words, beforeInit is too early, unless you delay the execution in a certain JS event (such as onload). You'd better use includes: after_body instead of beforeInit or includes: in_header.

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.