An interactive application showcases a sentence on the screen.
Users have the ability to select specific parts of the sentence and apply custom markup by clicking the Mark
button. The sentence should then reflect this action in real-time.
For example:
Input: A sample sentence for demonstration
Selection: sentence for
Desired output: A sample
<markup> sentence for </markup>
demonstration
Below is the code for the shiny app along with the relevant JavaScript function:
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;
}
Issue: Although the alert(result)
displays the desired output, the subsequent line fails to update the content
.
Are there alternative ways to achieve this functionality without relying on JavaScript? Please share your insights.