I try to combine two javascript functions into one variable so that I can call both in the DT::datatable initComplete option. The functions are working independently of each other, but when I combine them the table is not rendered.
JS function 1:
rownumber <- 8
jsc <- paste0("function() {
$(this.api().table().row(", rownumber, ").node()).addClass('selected');
this.api().table().row(", rownumber, ").node().scrollIntoView();
}")
JS function #2:
jsc2 <- "function(settings, json) {$(this.api().table().header()).css({'background-color': '#2c3e50', 'color': '#fff'});}"
JS function #3 (the combined one):
jsc3 <- paste0("function() {
$(this.api().table().row(", rownumber, ").node()).addClass('selected');
this.api().table().row(", rownumber, ").node().scrollIntoView();
}
function(settings, json) {$(this.api().table().header()).css({'background-color': '#2c3e50', 'color': '#fff'});}")
When I run the last one with the code below, I do not get the desired result of a colored header row and that the focused is scrolled to the 8th row.
mtcars %>% datatable(
options = list(
dom = 't',
paging = FALSE,
scrollX = TRUE,
scroller = TRUE,
paging = TRUE,
initComplete = JS(jsc3)
)
)
I appreciate if somebody can assist on how to combine those two functions into a line of code that will render properly in the DT::datatable.
initComplete needs one and only one JS callback. In your jsc3, you defined two functions. This cannot be accepted. You need to merge two functions to one, like below:
library(DT)
rownumber <- 8
jsc3 <- paste0("function() {
$(this.api().table().row(", rownumber, ").node()).addClass('selected');
this.api().table().row(", rownumber, ").node().scrollIntoView();
$(this.api().table().header()).css({'background-color': '#2c3e50', 'color': '#fff'});
}
")
mtcars %>% datatable(
options = list(
dom = 't',
paging = FALSE,
scrollX = TRUE,
scroller = TRUE,
paging = TRUE,
initComplete = JS(jsc3)
)
)