javascriptrshinyfullpage.jsshinyjs

update menuanchor of fullPage.js in R Shiny App from server side


I am using the fullPage package to create a Shiny App and I am facing the following issue : I would like to update from the server side the labels of the menu that are first defined in the pagePiling function of the ui part.

I have seen in the HTML code that the field that I should update is the one here below, but I don't know how to change it/access it in the server part of my app.

<ul id="tocMenu">
        <li data-menuanchor="test_page">
          <a href="#test_page">temp_title</a>
        </li>
      </ul>

I have the impression that this sould be achievable with javascript, but I don't know a lot about js ; among others, I have tried so far the following stuff :

library(fullPage)
library(shiny)
library(shinyjs)
library(shinyWidgets)
shinyApp(
  ui = pagePiling(
    shinyjs::useShinyjs(), 
    center = TRUE,
    sections.color = c(
      "#CFE2F3"
    ),
    menu = c(
      "temp_title" = "test_page"
    ),
    pageSection(
      menu="test_page",
      pickerInput("title",  multiple = F, selected=NULL,
                  choices = c("Title 1", "Title 2")),
    )
  ),
  server = function(input, output) {
    observeEvent(input$title, {
      # runjs("$('#fullpage').fullpage({
      #   anchors: ['test'],
      #   menu: '#tocMenu'});")
      runjs(paste0('document.getElementById("test_page").innerHTML = "', input$title, '";'))
    } ) 
  }
)

If anyone could help, I would be very grateful !

Thanks


Solution

  • The problem is that you use getElementById() but the menu title doesn't have an id, it has an href tag:

    enter image description here

    Therefore, you should use querySelectorAll() instead and specify the characteristics of the element you want to select (here, it's an element a that has href="#test_page"). Finally, this function returns a list of elements (this list only contains 1 element here), so you need to use [0] to select it.

    Here's your example fixed:

    library(fullPage)
    library(shiny)
    library(shinyjs)
    library(shinyWidgets)
    
    shinyApp(
      ui = pagePiling(
        shinyjs::useShinyjs(), 
        center = TRUE,
        sections.color = c(
          "#CFE2F3"
        ),
        menu = c(
          "temp_title" = "test_page"
        ),
        pageSection(
          menu="test_page",
          pickerInput("title",  multiple = F, selected=NULL,
                      choices = c("Title 1", "Title 2")),
        )
      ),
      server = function(input, output) {
        observeEvent(input$title, {
          # runjs("$('#fullpage').fullpage({
          #   anchors: ['test'],
          #   menu: '#tocMenu'});")
          runjs(paste0('document.querySelectorAll("a[href=\'#test_page\']")[0].innerHTML = "', input$title, '";'))
        } ) 
      }
    )