get ID of element under cursor in shiny

邮差的信 提交于 2020-01-25 11:59:07

问题


In my Shiny app, the user mouses over some HTML output which consists of several spans, like this:

<div id="mydiv">
    <span id="span1">foo</span>
    <span id="span2">bar</span>
</div>

I want to get the ID of the span which the user is currently mousing over as a shiny input$... I know there are lots of js ways to do it, jquery get element where the cursor is, but I don't know how to integrate with Shiny, e.g. by using shinyjs https://deanattali.com/shinyjs/extend.


回答1:


Like this, if I correctly understand:

library(shiny)

js <- "
$(document).ready(function(){
  $('span').on('mouseover', function(evt){
    Shiny.setInputValue('span', evt.target.id);
  });
})
"

ui <- basicPage(
  tags$head(tags$script(HTML(js))),
  tags$div(
    tags$span(id = "span1", "foo"),
    tags$span(id = "span2", "bar")
  ),
  br(),
  verbatimTextOutput("span")
)

server <- function(input, output){
  output[["span"]] <- renderPrint({
    input[["span"]]
  })
}

shinyApp(ui, server)


来源:https://stackoverflow.com/questions/58541195/get-id-of-element-under-cursor-in-shiny

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!