A shiny app displays a sentence.
When a user selects some part of sentence and clicks the Mark
button to add markup, the sentence should be updated to reflect the action.
Example:
Sample input: A sample sentence for demo
Selection: sentence for
Desired output: A sample <markup> sentence for </markup>
demo
Following is the shiny app code and the relevant JavaScript code:
library(shiny)
ui <- fluidPage(
tags$head(tags$script(src="addMarkup.js")),
titlePanel("Mark text selection"),
mainPanel(htmlOutput("content"),
actionButton("Mark", "Mark", onclick="addMarkup()")
)
)
server <- function(input, output) {
sentence <- "A sample sentence for demo"
output$content <- renderText(sentence)
}
shinyApp(ui = ui, server = server)
addMarkup.js
function addMarkup(){
var sent="";
sent= document.getElementById("content").innerHTML;
var selection="";
if(window.getSelection){
selection = window.getSelection().toString();
}
else if(document.selection && document.selection.type != "Control"){
selection = document.selection.createRange().text;
}
marked = "<markup>".concat(selection).concat("</markup>");
result = sent.replace(selection, marked);
alert(result);
document.getElementById("content").innerHTML = result;
}
Problem: The alert(result)
does show the desired output, but the subsequent line does not update the content
.
How can I achieve this functionality?
Please also suggest if a pure shiny solution exists (How can I achieve without involving JavaScript).