Home > Enterprise >  How to apply JS/ jQuery after element is visible in a shinyApp?
How to apply JS/ jQuery after element is visible in a shinyApp?

Time:03-01

First, as mentioned in that answer:

$(document).ready approach won't work because server will not render it outputs until the DOM is ready. Use session$onFlushed instead, with once parameter set to TRUE, then shiny will run the function only once, not on every session flush.

Right. Now, I have a actionButton (#btn3) that appears in the app when I click on another one (#btn1). However, jQuery doesn't work when this button appears after clicking on another one. I want to apply mouseover and mouseout effects in #btn3 when he appears.

My app:

library(shiny)

ui <- fluidPage(
  shinyjs::useShinyjs(),
  fluidRow(actionButton(inputId = "btn1", label = 'Press'), uiOutput("btn2"))
)

server <- function(input, output, session) {
  
  observeEvent(input$btn1, {
    output$btn2 <- renderUI({
      actionButton(
        inputId = "btn3",
        label = "",
        title = "Ver/ esconder análise",
        icon = icon('eye'),
        style = "color: #f2f2f2; background-color: #008cba;"
      )
    })
  })
  
  session$onFlushed(function() {
    shinyjs::runjs("$('#btn3').on('mouseover',function(){
    $(this).css({'color':'#020202','background-color':'#ffff00'});
    });
    $('#btn3').on('mouseout',function() {
    $(this).css({'color':'#f2f2f2','background-color':'#008cba'});
    });")
  }, once=TRUE)
  
}

shinyApp(ui, server) 

How to solve this?

CodePudding user response:

library(shiny)

js <- "
$(document).ready(function(){
  $('#btn3').on('mouseover', function(){
    $(this).css({'color': '#020202', 'background-color': '#ffff00'});
  }).on('mouseout', function() {
    $(this).css({'color': '#f2f2f2', 'background-color': '#008cba'});
  });
});
"


ui <- fluidPage(
  tags$head(tags$script(HTML(js))),
  br(),
  fluidRow(
    actionButton(
      inputId = "btn1", 
      label = 'Press',
      onclick = "$('#btn3').show()"
    ),
    actionButton(
      inputId = "btn3",
      label = "",
      title = "Ver/ esconder análise",
      icon = icon('eye'),
      style = "display: none; color: #f2f2f2; background-color: #008cba;"
    )
  )
)

server <- function(input, output, session) {
  
}

shinyApp(ui, server) 
  • Related