change body color by add a js function to shiny button

I want to add a function to the onclik of shiny button. I want to change body color when I click the shiny buttons(page 1, page 2 page 3), But I always get the last color of colors.I can not change any color by click the button.
I have add the js file to the dirctory which called www.

I want show a demo code that can show error which I got trouble:

  • javascript file part
function addloadevent(func) {
    var oldload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {

function add_onclick(){
    var want = document.getElementsByTagName('a');
    var colors = ['pink', 'skyblue', "blue"];
    function make_click(color) {
        var color2 = color; = color2;
                return false;
    for (let i = 0; i < want.length; i++) {
        want[i].onclick = make_click(colors[i]);

  • R code file

ui <- fluidPage(id = 'pageid',
                # tags$head(tags$script(src='col2.js')),
                tags$script(src = "col2.js"),
                tabsetPanel(id = 'p1',
                            tabPanel(title = 'page 1',
                            tabPanel(title = 'page 2',
                            tabPanel(title = 'page 3',

server <- function(input, output) {

shinyApp(ui = ui, server = server)

  • session information
R version 4.0.2 (2020-06-22)
Platform: x86_64-apple-darwin17.0 (64-bit)
Running under: macOS Catalina 10.15.6

Matrix products: default
BLAS:   /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRlapack.dylib

[1] zh_CN.UTF-8/zh_CN.UTF-8/zh_CN.UTF-8/C/zh_CN.UTF-8/zh_CN.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] shinyjs_2.0.0 shiny_1.5.0  

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.5      digest_0.6.25   withr_2.2.0     later_1.1.0.1   mime_0.9        R6_2.4.1       
 [7] jsonlite_1.7.0  xtable_1.8-4    magrittr_1.5    rlang_0.4.7     promises_1.1.1  tools_4.0.2    
[13] tinytex_0.25    httpuv_1.5.4    xfun_0.16       fastmap_1.0.1   compiler_4.0.2  htmltools_0.5.0

I have get the answer from stackoverflow :blush:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.