Shiny modules using pre-generated java script

shiny
shiny-modules

#1

I’m creating a shiny app that uses the following js:

// Credits: trestletech
// https://github.com/trestletech/ShinyChat/blob/master/sendOnEnter.js

// Sending on ENTER
jQuery(document).ready(function(){
  jQuery('#message_field').keypress(function(evt){
    if (evt.keyCode == 13){
      // Enter, simulate clicking send
      jQuery('#send').click();
    }
  });
});

// Scrolling down
var oldContent = null;
window.setInterval(function() {
  var elem = document.getElementById('chatbox');
  if (oldContent != elem.innerHTML){
    scrollToBottom();
  }
  oldContent = elem.innerHTML;
}, 300);

function scrollToBottom(){
  var elem = document.getElementById('chatbox');
  elem.scrollTop = elem.scrollHeight;
}

In my shiny UI i have the following code to use the js

tags$script(src = './script.js')

The problem is that if i create a module, the java script should use the id ns(chatbox) instead of just chatbox. Is there a way to fix this? I found this discussion, but I’m having troubles following the proposed solution.


#2

I had to create a function that writes the js code taking the elements id’s as arguments:

jsclicktoenter <- function(send, chatboxid, message_field){

  first <- "shinyjs.init = function() {
  // Sending on ENTER
  jQuery(document).ready(function(){
  jQuery('#"

  second <- "').keypress(function(evt){
  if (evt.keyCode == 13){
  // Enter, simulate clicking send
  jQuery('#"



  third <- "').click();
  }
  });
  });

  // Scrolling down
  var oldContent = null;
  window.setInterval(function() {
  var elem = document.getElementById('"

fourth <- "');
if (oldContent != elem.innerHTML){
scrollToBottom();
}
oldContent = elem.innerHTML;
  }, 300);

function scrollToBottom(){
var elem = document.getElementById('chatbox');
elem.scrollTop = elem.scrollHeight;
}
}"

  jscode <- paste0(first, message_field, second, send, third,chatboxid,fourth)

  return(jscode)
}

In my ui module I call that function

jscode <- jsclicktoenter(send = ns("send"), chatboxid = ns("chatbox"),
                                      message_field = ns("message_field"))

and shinyjs does the magic:

    shinyjs::useShinyjs(),
    shinyjs::extendShinyjs(text = jscode)