Search code examples
javascriptrshiny

How to get the cursor position in a Shiny textareaInput


does anyone know how I can, inside a shiny application, get the cursor position inside a textAreaInput ?

library(shiny)

ui <- fluidPage(
  textAreaInput("hop"
                ,label="textarea",value = "Supercalifragilisticexpialidocious"),
  verbatimTextOutput("out")
)

server <- function(input, output, session) {

  output$out <- renderText({
    "here I would like to get the cursor position (an interger?) \n inside que textArea"

  })

}

shinyApp(ui, server)

I think I have to use javascript, but I don't know where to start.

Regards


Solution

  • this is a solution I found :

    library(shiny)
    
    ui <- fluidPage(tags$head(tags$script(
      'Shiny.addCustomMessageHandler("prout",
      function(NULL) {
    
       var ctl = document.getElementById("hop");
        var startPos = ctl.selectionStart;
      var endPos = ctl.selectionEnd;
      alert(startPos + ", " + endPos);
    
      });'
        )),
      textAreaInput("hop"
                    ,label="textarea",value = "Supercalifragilisticexpialidocious"),
      verbatimTextOutput("out"),
      actionButton("hop","hop")
    )
    
    server <- function(input, output, session) {
    
      output$out <- renderText({
        "here I would like to get the cursor position (an interger?) \n inside que textArea"
    
      })
    
      observeEvent(input$hop,{
        message("hop")
        session$sendCustomMessage(type="prout",message=list(NULL))
      })
    }
    
    shinyApp(ui, server)