admin管理员组

文章数量:1435822

I've been trying to customise shinyWidgets::noUiSliderInput with JS so that its tooltips are editable and the slider reacts to user inputs—something exactly like the example here, but in Shiny.

I created this shiny app to play with JS:

library(shiny)

ui <- fluidPage(
  tags$h2("Shiny noUiSlider with Editable Tooltips"),
  
  shinyWidgets::noUiSliderInput(
    inputId = "slider_id",
    value = c(10, 20),
    min = 0,
    max = 50
  ),
  
  # JS to create the slider with editable tooltips
  tags$head(tags$script(HTML(
    "$(document).ready((function() {
      var slider = document.getElementById('slider_id');
    
      function sp(event) { event.stopPropagation(); }

      function makeTT(i, slider) {
        var tooltip = document.createElement('div'),
            input = document.createElement('input');

        tooltip.className = 'noUi-tooltip';
        tooltip.appendChild(input);

        input.addEventListener('change', function() {
          var values = [null, null];
          values[i] = this.value;
          slider.noUiSlider.set(values);
        });

        input.addEventListener('mousedown', sp);
        input.addEventListener('touchstart', sp);
        input.addEventListener('pointerdown', sp);
        input.addEventListener('MSPointerDown', sp);

        slider.querySelector(i ? '.noUi-handle-upper' : '.noUi-handle-lower').appendChild(tooltip);
        return input;
      }

      // Create tooltip inputs
      var tooltipInputs = [makeTT(0, slider), makeTT(1, slider)];
    
      slider.noUiSlider.on('update', function(values, handle) {
        tooltipInputs[handle].value = values[handle];
      });
    })())"
  )))
)

# Server logic
server <- function(input, output, session) {
  observe({
    print(input$slider_id)  # For debugging
  })
}
shinyApp(ui = ui, server = server)

It doesn't do what I expect, and I get this error: null is not an object (evaluating 'slider.querySelector') when the following part of the makeTT function is being executed:

slider.querySelector(i ? '.noUi-handle-upper' : '.noUi-handle-lower').appendChild(tooltip);

That leads me to think the way I defined slider here var slider = document.getElementById('slider_id'); is incorrect (as it returns NULL, as the error says). But I'm not sure how else I should refer to this object.

本文标签: javascriptEditable Tooltips in shinyWidgetsnoUiSliderInputStack Overflow