kableExtra disabling javascript in bookdown/rmarkdown documents?

Hello, I'm trying to use the following javascript to selectively hide some code chunks that don't really matter, but might be of interest to some readers. I originally found the script here: https://stackoverflow.com/questions/37755037/how-to-add-code-folding-to-output-chunks-in-rmarkdown-html-documents/37839683#37839683 and it works perfectly fine... until I try to use kableExtra elsewhere in the document.

Here is a trimmed down rmarkdown file with YAML header, where the hide/show source code script works (please note I had to replace ` with ' to get the code to display correctly on this forum)

site: bookdown::bookdown_site
    fig_caption: yes
    df_print: paged
      in_header: "./common/hideOutput.js"

# Prerequisites

This is a _sample_ book written in **Markdown**. You can use anything that Pandoc's Markdown supports, e.g., a math equation $a^2 + b^2 = c^2$.

#dt <- mtcars[1:5, 1:6]
#dt %>%
#  kable() %>%
#  kable_styling()


<div class="fold s">
'''{r, eval=FALSE}
# Some code I don't want to show but to be accessible for interested readers...
mtcars %>%
  group_by(mpg) %>%
  summarise(nonsense = mean(cyl))

If you uncomment the dt <--.... lines, the script no longer works. If I switch the two code chunks around, so kableExtra loads, and is used after the <div> it still doesn't work! I haven't the foggiest idea of what is going on....

This is what my hideOutput.js file looks like:

$(document).ready(function() {

  $chunks = $('.fold');

  $chunks.each(function () {

    // add button to source code chunks
    if ( $(this).hasClass('s') ) {
      $('pre.r', this).prepend("<div class=\"showopt\">Show Source</div><br style=\"line-height:22px;\"/>");
      $('pre.r', this).children('code').attr('class', 'folded');

    // add button to output chunks
    if ( $(this).hasClass('o') ) {
      $('pre:not(.r)', this).has('code').prepend("<div class=\"showopt\">Show Output</div><br style=\"line-height:22px;\"/>");
      $('pre:not(.r)', this).children('code:not(r)').addClass('folded');

      // add button to plots
      $(this).find('img').wrap('<pre class=\"plot\"></pre>');
      $('pre.plot', this).prepend("<div class=\"showopt\">Show Plot</div><br style=\"line-height:22px;\"/>");
      $('pre.plot', this).children('img').addClass('folded');


  // hide all chunks when document is loaded
  $('.folded').css('display', 'none')

  // function to toggle the visibility
  $('.showopt').click(function() {
    var label = $(this).html();
    if (label.indexOf("Show") >= 0) {
      $(this).html(label.replace("Show", "Hide"));
    } else {
      $(this).html(label.replace("Hide", "Show"));
    $(this).siblings('code, img').slideToggle('fast', 'swing');