How to dynamically append a string text to the body of a shiny app?

1.1k views Asked by At

I am trying append a reactive text (the color name from selectInput) to the body of a shiny app after tags$h3. I guess this is more a jquery issue, but right now it keeps adding the selected color rather than displaying the string "reactively".

What I would like instead is to have the string inside h3.colorLabel to be replaced.

ui.R

library(shiny)
jsCode <- "shinyjs.pageCol = function(params){
$('body').css('background', params);
/*$('.colorName').after('<h3></h3>').addClass('colorLabel');
$('h3.colorLabel').replaceWith('<h3>'+params+'</h3>').addClass('colorLabel');
*/
$('h3.colorName').after('<h3>'+params+'</h3>').addClass('colorLabel');
};
"

shinyUI( fluidPage(
  useShinyjs(),
  extendShinyjs(text = jsCode),
  selectInput("col", "Colour:",
              c("white", "yellow", "red", "blue", "purple")),
  tags$h3('Just in case you are color-blind, the background color is:', class='colorName')
))

server.R

library(shiny)
library(shinyjs)

shinyServer(


    function(input,output,session) {

      observeEvent(input$col, {
         js$pageCol(input$col)
       })
      })
1

There are 1 answers

0
Mike Wise On BEST ANSWER

I think this is what you want. It edits the innerhtml of the h3' element with thecolorLabel` class. I also added a corresponding empty initialized element to the ui code so there would be something to edit.

library(shiny)
library(shinyjs)

jsCode <- "shinyjs.pageCol = function(params){
$('body').css('background', params);
$('h3.colorLabel').text(params); 
};
"

u <- shinyUI(fluidPage(
  useShinyjs(),
  extendShinyjs(text = jsCode),
  selectInput("col","Colour:",
              c("white","yellow","red","blue","purple")),
  tags$h3('Just in case you are color-blind, the background color is:',class ='colorName'),
  tags$h3('',class = 'colorLabel')
))


s <- shinyServer(


  function(input,output,session) {

    observeEvent(input$col, {
      js$pageCol(input$col)
    })
  })
shinyApp(ui = u,server = s)

yielding:

enter image description here

And this is what is being edited internally:

enter image description here