Mark Heckmann
Mark Heckmann

Reputation: 11431

Adding shiny navbar element which triggers JS when clicked

This navigation bar is what I want:

enter image description here

However, clicking Test, should not open a panel, but just run some JS code, in this case create an alert. Test should look like a standard navbar element. This is what I tried ...

library(shiny)

ui <- navbarPage(title = "test", inverse = T,
              tabPanel("Simulate", "simulate panel"),
              tabPanel("Test", "test panel"), 

             #------ Add onclick action ------#
             tags$script("var a = $('.navbar-nav  li:nth-child(2) a');
               a.attr('data-toggle', 'noclass');
               a.click(function() {
                  alert('link clicked');
               });")
  )

server <- function(input, output) { 
}

shinyApp(ui = ui, server = server)

and it basically works, but when looking at the ui output, an additional <li>element is appended, which does not need to be there.

   <ul class="nav navbar-nav">
      <li class="active">
        <a href="#tab-9138-1" data-toggle="tab" data-value="Simulate">Simulate</a>
      </li>
      <li>
        <a href="#tab-9138-2" data-toggle="tab" data-value="Test">Test</a>
      </li>
      <li>
        <a href="#tab-9138-3" data-toggle="tab"></a>
      </li>
    </ul>

My questions:

  1. How can I create a link in the navbar avoiding the extra li element.
  2. Is there a better way to achieve this, i.e. without messing so much with the li attributes?

Upvotes: 2

Views: 743

Answers (1)

jdharrison
jdharrison

Reputation: 30425

You can place the script in the header of the navbarPage and the extra li will not be created. You can add an id to the navbarPage and use that to reference the element in your script:

library(shiny)

ui <- navbarPage(title = "test", id = "nbpID", inverse = T,
                 header = tags$script("var a = $('#nbpID a[data-value=\"Test\"]');
                             a.attr('data-toggle', 'noclass');
                             a.click(function() {
                             alert('link clicked');
                             });"),
                 tabPanel("Simulate", "simulate panel"),
                 tabPanel("Test", "test panel")
)

server <- function(input, output) { 
}

shinyApp(ui = ui, server = server)

Upvotes: 2

Related Questions