Search code examples
rshinyshinyjs

Change html with an animation effect in a shiny app


I am having a shiny app with some ui elements. Is there a way to replace some HTML (e.g. div / div content) with an animation effect, similar to what shinyjs::show(anim=T) does?

library(shiny)
library(shinyjs)

ui <- fluidPage(
  shinyjs::useShinyjs(),
  
  actionButton("change","change"),
  tags$div(id="someDiv",
           "test"),
  
  hidden(tags$div(id="withAnim", "Displayed with animation"))
  
)

server <- function(input, output) {

  observeEvent(input$change, {
    shinyjs::html("someDiv", "changed without animation")
    shinyjs::delay(1000, show("withAnim", anim=T, animType="fade"))
  })
 
}

shinyApp(ui = ui, server = server)

Solution

  • the shinyjs::html doesn't provide this utility. We can write our own js code and use shinyjs::runjs to run it when button is clicked.

    library(shiny)
    library(shinyjs)
    
    ui <- fluidPage(
      shinyjs::useShinyjs(),
      
      actionButton("change","change"),
      tags$div(id="someDiv",
               "test"),
      
      hidden(tags$div(id="withAnim", "Displayed with animation"))
      
    )
    
    server <- function(input, output) {
      
      observeEvent(input$change, {
        shinyjs::runjs("$('#someDiv').fadeOut(500, function(){$(this).text('changed without animation').fadeIn();})")
        shinyjs::delay(1000, show("withAnim", anim=T, animType="fade"))
      })
      
    }
    
    shinyApp(ui = ui, server = server)
    

    enter image description here