Skip to content

Instantly share code, notes, and snippets.

@McClellandLegge
Last active April 27, 2018 20:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save McClellandLegge/71472adcfe36270ec876b455beba2bdb to your computer and use it in GitHub Desktop.
Save McClellandLegge/71472adcfe36270ec876b455beba2bdb to your computer and use it in GitHub Desktop.
Dynamic Animation Speed
library("shiny")
ui <- fluidPage(
includeScript('shiny-events.js'),
numericInput("min", "Min", value = 0, min = 0, max = 10),
numericInput("max", "Max", value = 100, min = 100, max = 200),
sliderInput("speed", "Animation Speed", value = 100, ticks = FALSE, round = 50, min = 50, max = 1000),
uiOutput('slider_div'),
br(),
htmlOutput('displaySpeed')
)
server <- function(input, output, session) {
output$slider_div <- renderUI({
sliderInput(
inputId = 'slider'
, label = 'Slider'
, min = input$min
, max = input$max
, value = isolate(animation$value)
, animate = animationOptions(interval = animation$speed, loop = TRUE)
)
})
# update animation interval
animation <- reactiveValues(speed = 100, value = 1)
observeEvent(input$speed, {
invalidateLater(500, session)
animation$value <- input$slider
animation$speed <- input$speed
})
output$displaySpeed <- renderText({
HTML("Current interval:", animation$speed)
})
observeEvent(input$speed, {
session$sendCustomMessage('resume', TRUE)
})
observeEvent(input$min | input$max, {
animation$value <- input$slider
})
}
shinyApp(ui, server)
$(function() {
var renders = 0;
var press_play = false;
$(document).on({
// COULD ALSO DO $('#slider_div').on('shiny:value', function() {...})
'shiny:value': function(event) {
switch (event.name) {
case 'slider_div':
// WONT RESUME IF THE RENDER WAS DUE TO SOMETHING ELSE
if (renders > 0 && press_play) {
setTimeout(function() {
$('.slider-animate-button').click();
}, 200);
press_play = false;
} else {
renders = 1;
}
break;
default:
}
}
});
Shiny.addCustomMessageHandler('resume', function(message) {
press_play = true;
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment