I have a shiny app, where I want to change the navbar classes when the user scrolls down. This is done using custom vanilla JS which adds an eventListener (see also https://jsfiddle.net/t317akfb/ for a fully working version).
When I include the javascript in R, I see that it is found and executed (it prints the "START"
message in the browser console), but the event listener does not work when I scroll (like it did in the jsfiddle above).
When I manually call the document.getElementsByClassName("navbar")...
code, it works, similarly, if I add the navbar-red
class to the navbar, it also turns red.
MWE
library(shiny)
library(bslib)
js <- 'let attop = true
console.log("START")
document.addEventListener("scroll", (event) => {
console.log("SCROLL");
if (window.scrollY != 0 & attop) {
attop = false;
let col = document.getElementsByClassName("navbar");
for (let i = 0; i < col.length; i++) {
col[i].classList.add("navbar-red");
}
console.log("Not At Top");
} else if (window.scrollY == 0) {
attop = true;
let col = document.getElementsByClassName("navbar");
for (let i = 0; i < col.length; i++) {
col[i].classList.remove("navbar-red");
}
console.log("At Top!");
}
});
'
ui <- page_navbar(
theme = bs_theme() |>
bs_add_rules("nav.navbar.navbar-inverse.navbar-red { background-color: red !important; }"),
id = "navbar",
title = "NAVBAR",
tabPanel(
title = "hello",
tags$head(tags$script(HTML(js))),
h2("header"),
div(style = "height: 200vh; background-color: lightgray;")
)
)
shinyApp(ui, server = function(input, output, session) {})
Edit - bslib
as a potential culprit
I have replicated the app in pure shiny without bslib
and it works
eg
library(shiny)
js <- 'let attop = true
console.log("START")
document.addEventListener("scroll", (event) => {
console.log("SCROLL");
if (window.scrollY != 0 & attop) {
attop = false;
let col = document.getElementsByClassName("navbar");
for (let i = 0; i < col.length; i++) {
col[i].classList.add("navbar-red");
}
console.log("Not At Top");
} else if (window.scrollY == 0) {
attop = true;
let col = document.getElementsByClassName("navbar");
for (let i = 0; i < col.length; i++) {
col[i].classList.remove("navbar-red");
}
console.log("At Top!");
}
});
'
css <- '.navbar-red { background-color: red !important; }'
ui <- navbarPage(
title = "",
tabPanel(
title = "test tab",
tags$head(tags$script(HTML(js))),
tags$head(tags$style(HTML(css))),
h2("header"),
div(style = "height: 200vh; background-color: lightgray;")
),
selected = "test tab",
position = c("fixed-top")
)
server <- function(input, output, session) {
}
shinyApp(ui, server)
Upgrading
bslib
to 0.5.1.9000 (currently the dev version on github) resolves the issue.I just needed to update the css to this identifier
nav.navbar.navbar-red
.Not sure what caused the issue though.
Edit
When using a sidebar in the
page_navbar
, the scrolling event listener does not work.