3

Purpose: I needed a way to add custom labels (0, 0.33, 0.66, 1) to a Shiny slider. I modified the code from the following post: R Shiny date slider animation by month (currently by day)

Question: How can I pass the current slider value into a Shiny object? I tried to modify my code with this post but was unsuccessful: http://ionden.com/a/plugins/ion.rangeslider/demo_interactions.html

Please note that I am very new to Javascript and my code cannot include any additional packages.

ui

# ui
library(shiny)
shinyUI(fluidPage(
  br(),
  uiOutput("mySlider"),
  verbatimTextOutput("myValue"))
)

server

# server    
x <- c(0,0.33,0.66,1) # slider values

# function to create slider
sliderValues <- function (inputId, values){

  sliderTag <- tags$div(
    do.call(tags$input, list(type = "single",
                             id = "inputId",
                             value = x)),
  tags$script(
    HTML('$("#mySlider").ionRangeSlider({
         grid: true,
         values: [0,0.33,0.66,1]});'))
    )

  dep <- htmltools::htmlDependency(
    "ionrangeslider",
    "2.1.12",
    c(href = "shared/ionrangeslider"),
    script = "js/ion.rangeSlider.min.js",
    stylesheet = c(
      "css/ion.rangeSlider.css",
      "css/ion.rangeSlider.skinShiny.css"
    ))
  htmltools::attachDependencies(sliderTag, dep)
}

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

  output$mySlider <- renderUI({
    sliderValues(inputId = "mySlider",
                 values = x)
  })

  output$myValue <- renderPrint({
    print(as.numeric(unlist(input$mySlider)))
  })
}
Megan W.
  • 31
  • 3

0 Answers0