'How can I add 'Read more' and 'Read less' functionality for long text in R Shiny?

I am trying to add 'Read more' or 'Read less' functionality for long text in my Shiny app. My knowledge related to JS/ html is limited, so if there is any assist regarding communicating information between shiny, js or html that would be helpful.

I was referring this tutorial but not able to understand how to implement the same in the shiny app.

I was trying with following code.

library(shiny)
library(htmltools)
library(htmlwidgets)

jscode <- 
  'shinyjs.myFunction = function() {
    var dots = document.getElementById("dots");
    var moreText = document.getElementById("more");
    var btnText = document.getElementById("myBtn");

    if (dots.style.display === "none") {
      dots.style.display = "inline";
      btnText.innerHTML = "Read more";
      moreText.style.display = "none";
    } else {
      dots.style.display = "none";
      btnText.innerHTML = "Read less";
      moreText.style.display = "inline";
    }
  }'

css <- "#more {display: none;}"

ui <- fluidPage(
  shinyjs::useShinyjs(),
  shinyjs::extendShinyjs(
    text = jscode,
    functions = c('myFunction')
  ),
  shinyjs::inlineCSS(css),
  uiOutput('test')
)

server <- function(input, output, session) {
  
  output$test <- renderUI({
    
    HTML('<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scel<span id="dots">...</span><span id="more">erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.</span></p>

<button onclick="myFunction()" id="myBtn">Read more</button>')
  })
}

shinyApp(ui, server)

Thanks in advance.



Solution 1:[1]

If you want to avoid JS you could use the details and summary tags in HTML.

Shiny example

Here is a small example implemented using only Shiny-code:

library(shiny)

ui <- fluidPage(

    tags$p("Some information"),
    tags$details(
        tags$summary("Read more"),
        "More information"
    ) 
    
)

server <- function(input, output) {}

shinyApp(ui = ui, server = server)

HTML example

If you want to use HTML directly you could use add this to your server inside the HTML() function in Shiny:

<p>Some information</p>
<details>
  <summary>Read more</summary>
  More information
</details>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jpiversen