Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

71
Visualizações
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.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Here is a possibility:

library(shiny)

CSS <- "
.morecontent span {
    display: none;
}
.morelink {
    display: block;
}
"

JS <- '
$(document).ready(function() {
    // Configure/customize these variables.
    var showChar = 100;  // How many characters are shown by default
    var ellipsestext = "...";
    var moretext = "Show more >";
    var lesstext = "Show less";
    
    $(".more").each(function() {
        var content = $(this).html();
        if(content.length > showChar) {
            var c = content.substr(0, showChar);
            var h = content.substr(showChar, content.length - showChar);
            var html = c + "<span class=\\\"moreellipses\\\">" + ellipsestext 
              + "&nbsp;</span><span class=\\\"morecontent\\\"><span>" + h 
              + "</span>&nbsp;&nbsp;<a href=\\\"\\\" class=\\\"morelink\\\">" 
              + moretext + "</a></span>";
            $(this).html(html);
        }
    });
 
    $(".morelink").click(function(){
        if($(this).hasClass("less")) {
            $(this).removeClass("less");
            $(this).html(moretext);
        } else {
            $(this).addClass("less");
            $(this).html(lesstext);
        }
        $(this).parent().prev().toggle();
        $(this).prev().toggle();
        return false;
    });
});
'

ui <- fluidPage(
  tags$head(
    tags$style(HTML(CSS)), 
    tags$script(HTML(JS))
  ),
  
  tags$span(
    class = "more",
    "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
  )
  
)

server <- function(input, output){}

shinyApp(ui, server)

enter image description here

source: codepen.io/maxds/pen/WNrvZY

about 4 years ago · Juan Pablo Isaza Relatório

0

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>
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda