What is the best way to include my JavaScript code in a shiny app to ensure all hyperlinks are acknowledged?

Is there a way to query all links using an external script that I integrate into the HTML via renderUI()? Currently, I am getting an empty NodeList []. Could it be related to where I include the script?

I have attempted the following setup:

R Shiny Script

library(shiny)

ui = navbarPage(
  title = "Test",  
  id = "test", 
  selected = "One", 
  footer = tagList(
    tags$script(src = "custom.js")),
  
  tabPanel(title = "One&quoqrt;,
    
           
    div("some links", style = "margin-top: 6rem;"),
    div(uiOutput(outputId = "test_ui")),
    
    
  )
  
)

server = function(input, output, session){
  
  
  output$test_ui  = renderUI({
    
    
    
    tagList(
      div(class = "link-section",
          tags$a("link_one"),
          tags$a("link_two"),
          tags$a("link_three"))
    )
    
  })
  
  
  
  
}
shinyApp(ui = ui, server = server, options = list(port = 3838, host = '0.0.0.0'))

JS Script (located in www folder of app directory)

let links = document.querySelectorAll("a.link-section");
console.log(links);

Answer №1

Implementing Shiny with shinyjs

In order to utilize a JavaScript function in R using shinyjs, the function name must be prefixed by shinyjs.. This allows it to be recognized by the functions parameter of shinyjs::extendShinyjs() and called in R through js$MySelection().

A specific approach I've employed is

shiny::onFlushed(function() { js$MySelection() })

"onFlushed registers a function that will be called after Shiny flushes the reactive system."

custom.js:

shinyjs.MySelection=function() {
  let links = document.querySelectorAll(".link-section a");
  console.log(links);
}

app.R:

library(shiny)
library(shinyjs)

ui =fluidPage(
  div(
    useShinyjs(),
    shinyjs::extendShinyjs(
      script = "custom.js", # without www
      functions = c("MySelection")
    ),
    navbarPage(
      title = "Test",  
      id = "test", 
      selected = "One", 
      
      tabPanel(title = "One",
               
               div("some links", style = "margin-top: 6rem;"),
               div(uiOutput(outputId = "test_ui"))
               
      )
      
    )
    
  )
)

server = function(input, output, session){
  
  output$test_ui  = renderUI({
    tagList(
      div(class = "link-section",
          tags$a("link_one"),
          tags$a("link_two"),
          tags$a("link_three")
          # in case of more delayed events or interactions : 
          # , shinyjs::hidden( textInput("hiddenInput","hiddenlabel"))
      ),
    )
    
  })

  # in case of more delayed events or interactions : 
  # observeEvent(input$hiddenInput,{
  #   js$MySelection()  
  # })
  
  shiny::onFlushed(
    function() {
      js$MySelection()  
    }
  )
}

shinyApp(ui = ui, server = server)

Utilizing Pure Shiny without shinyjs

  • Call javascript function on page load in R shiny

custom.js:

$(document ).on("shiny:sessioninitialized", function(event) {
  MySelection=function() {
    let links = document.querySelectorAll(".link-section a");
    console.log(links);
  }
}) 

app.R:

library(shiny)
ui =fluidPage(
  div(

    tags$head(tags$script(type="text/javascript",src="custom.js")),
    navbarPage(
      title = "Test",  
      id = "test", 
      selected = "One", 
      
      tabPanel(title = "One",
               
               div("some links", style = "margin-top: 6rem;"),
               div(uiOutput(outputId = "test_ui"))
               
      )
      
    )
    
  )
)

server = function(input, output, session){
  
  output$test_ui  = renderUI({
    tagList(
      div(class = "link-section",
          tags$a("link_one"),
          tags$a("link_two"),
          tags$a("link_three")
      ),
      tags$script(type="text/javascript", "MySelection()")
    )
    
  })
  
}

shinyApp(ui = ui, server = server)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Managing backslashes during the processing of JSON

I am currently facing an issue with a JSON string that I am trying to parse using the JSON.parse method. The problem seems to be related to the presence of backslashes and parentheses in the string, which results in an 'invalid character' error. ...

Executed a function upon clicking when the component was mounted

When working with React JS, if you use list object mapping like this: const deleteUser = (email) => { alert(email); } const userList = users.map((user) => <li key={user._id}> {user.Name} {isAdmin ...

What is the best way to create a fading footer effect on scroll using jQuery?

Why is my footer not fading in after 1000px like I want it to? Instead, it appears immediately on the screen. I attempted using fadeIn() in jQuery but had no luck. I also tried to make it disappear with fadeOut(), again with no success. Am I missing someth ...

An effective way to retrieve the URL of a page referrer and inject the content into a div is by utilizing jQuery's .load method

I am trying to set up a download page feature on my WordPress blog. I need to extract an HTML element with the id="download" from any URL that directed to the download page. Can someone help me with this task? I've included the code below, but unfort ...

Creating a textbox with pre-filled content

Seeking assistance with a Java compiler app I am developing through phonegap. Need help setting the default Java Class name in a textarea without it disappearing. This is what I have: <div> <label for="source">Source Code:</label> ...

JavaScript failing to link an element to the object

const modifyTimestamp = async (request, response) => { try { const { user: userid } = request; if (!ObjectId.isValid(userid)) throw new Error('invalid objectid'); const now = moment().format(); const date = new Date(now); ...

Angular Starter Kit

When starting with Angular.js, there are various boilerplate kits available such as angular-seed, some incorporating requirejs and more. However, many of the options I've come across seem to be outdated. As a newcomer to Angular, I'm wondering if ...

Which specific technological platform or framework would be most suitable for constructing a similar project?

https://i.stack.imgur.com/LL1g9.png Looking at the image provided, my goal is to allow users to navigate between pages on the Home page without having to refresh the entire browser window. I believe this can be achieved using Ajax technology, am I correct ...

When using JavaScript, the results of stringifying an array may not always align with

Can someone please assist with a strange issue I am experiencing in JavaScript? After clicking on the 'test' link, an alert pops up displaying: "[]" I was actually expecting to see something like: "[{'temp':25},{'thermState' ...

Looking for assistance with reviewing and optimizing Angular UI-Router implementation

I'm currently facing an issue with setting up routing for my angular portfolio. Despite checking my code against a previous app, I am unable to identify the error as there are no console logs when I compile. Can someone please review my code layout an ...

Having trouble with importing a TypeScript class: encountering a "cannot resolve" error message

Could you lend me your expertise? I'm puzzled by this issue that seems to be quite simple and straightforward: export class Rectangle { height: number = 0 width: number = 0 constructor(height: number, width: number) { this. ...

Troubleshooting the issue with utilizing the ng-repeat directive to loop through images in Angular JS

Embarking on my initial website development journey with Java and Spring Boot, I've hit a stumbling block in the front-end realm. Being a newbie, I'm struggling to identify and resolve the issue at hand. Problem title: How do I ...

The data seems to have disappeared from the HTTP requests in my Express and Mongoose project

I'm currently working on some files for a recipe app project. One of the files is recipe.js, where I have defined the Mongoose Schema for recipes and comments. The code snippet from the file looks like this: const express = require('express&apos ...

What is the solution for resolving the "Module Not Found" error when using Node.js and React?

While working on a website with react.js and tailwindcss, everything was working fine on localhost yesterday. However, without making any changes, I am now encountering an error message stating, "Cannot find module." P.S.: Is there an alternative method t ...

What if there was a magical jQuery method that could automatically trigger a callback function? What could it possibly be named?

Is there a way to load only images and iframes, similar to the .load() function? I want to automatically add a selector element into the "this" variable for this purpose. $('document').ready(function({ $('a').<Something to trigg ...

Using Inline Styling to Showcase a Background Image in a REACTJS Component

import React from 'react'; import Slick from 'react-slick'; import style from './Slider.module.css'; import {Link} from 'react-router-dom'; const SliderTemplates = (props) => { let template = null; const ...

What is the significance of using parentheses around a function in JavaScript?

Currently, I am developing an application using Java and JavaScript, and while reviewing some code today, I came across a segment that seemed confusing to me. var myVariable = (function(configObj){ var width = configObj.width; var height = config ...

Converting a text area into a file and saving it as a draft in the cloud with the

Can content from a text area be converted into a file of any chosen format and saved in the cloud? Additionally, should every modification made in the text area automatically update the corresponding file stored in the cloud? ...

Why is it that this JavaScript isn't working as intended in the popup form?

</br> s_foot"> * use ajax.jquery as control event. like $("#save").click(function(){.....}); <script type="text/javascript>" var wp; var position; var pid; var product_name; var production_date; In this script, I am attempting to re ...

How to clear a 24-hour-old template from the Angular 1 cache?

I have implemented the following rule to clear template cache in my AngularJS application: myApp.run(function ($rootScope, $templateCache) { $rootScope.$on('$viewContentLoaded', function() { $templateCache.removeAll(); }); }); Howe ...