My question is similar to this question, which asks how to set default filter selection in crosstalk::filter_select
in R
. However, I need to do the default select for crosstalk::filter_slider
for a date column. I have created a reproducible example with dummy data, filters and working default selection for the categorical filter. I would like to be able to do something similar for the date slider. How should I change my JavaScript so that, for example, the date range between tomorrow and the date after tomorrow is selected?
library(crosstalk)
library(htmltools)
# dummy data
dat <- data.frame(
date = Sys.Date() + 0:4,
letter = letters[1:5],
number = 0:4 + 1
)
# shared data
dat_shared <- crosstalk::SharedData$new(dat)
# custom js (contains unfinised code for date filter!)
custom_js <- shiny::tags$script('
// this is not complete and it does not work
function filter_date(){
document.getElementById("date")
}
$(document).ready(filter_date);
// this is an example how a default selection can be done using JS which works
// it selects a for the filter (the default is that nothing is selected)
// I want to do something similar, but for a date filter
function filter_cat(){
document.getElementById("filter_cat").getElementsByClassName("selectized")[0].selectize.setValue("a",false)
}
$(document).ready(filter_cat);
'
)
# filters for the widget
filter_cat <- crosstalk::filter_select(
"filter_cat", "Select a letter",
dat_shared, ~letter, multiple = F
)
filter_date <- crosstalk::filter_slider(
"filter_date", "Date",
dat_shared, ~date
)
# showing the widget in RStudio
htmltools::browsable(htmltools::tagList(
custom_js, filter_date, filter_cat
))
@Jonathan Nolan's code is good for setting values for numeric filters. Here is a version for a date filter.
library(crosstalk)
library(htmltools)
# dummy data
dat <- data.frame(
date = Sys.Date() + 0:4,
letter = letters[1:5],
number = 0:4 + 1
)
# shared data
dat_shared <- crosstalk::SharedData$new(dat)
# custom js
custom_js <- shiny::tags$script(paste0('
$(document).ready(function() {
var sliderInstance = $("#name_of_slider input").data("ionRangeSlider");
sliderInstance.update({
from: ', as.numeric(as.POSIXct( Sys.Date() + 1 )) * 1000, ',
to: ', as.numeric(as.POSIXct( Sys.Date() + 2 )) * 1000, '
});
});
'))
filter_date <- filter_slider("name_of_slider","Slider label", dat_shared, ~date)
htmltools::browsable(htmltools::tagList(
custom_js, filter_date
))