Trigger a JavaScript function upon page load within an R Shiny application

I have included references to css and javascript files in the code below:

tags$link(rel="stylesheet", type="text/css", href="rtp.css"),
  tags$script(type="text/javascript", src = "rtp.js"),

How can I successfully call a javascript function that is defined in "rtp.js"? I attempted to do so using the following code:

tags$script(type="text/javascript", src = "myfunction()")

(but it did not work as expected).

Answer №1

If you want to incorporate custom JavaScript functions at the beginning of your application, you can utilize the JS() function from the htmlwidgets package (which is likely included by default in shiny).

To add a function that runs when the application starts:

tags$script(JS('alert("initialized!")'))
tags$script(JS('myfunction()'))

If the myfunction() script is located in an external file, import it first and then execute it:

tags$script(type="text/javascript", src = "rtp.js"),
tags$script(JS('myfunction())'))

Answer №2

When using the src="foo" attribute, you are specifying that the script source should be retrieved from a file named foo. However, if you want to include inline code instead, you can pass an unnamed argument to the tags$script function:

tags$script(type="text/javascript", "myfunction()")

# <script type="text/javascript">myfunction()</script>

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

Customizing tab menu functionality for specific click actions

I have created a simple HTML tab menu with JavaScript that allows for changing content when tabs are clicked. test.html <!DOCTYPE html> <html> <head> <title>My Menu Test</title> <style type="text/css" media="all"& ...

What is the best way to introduce a time delay between two JavaScript functions?

Here is some JavaScript code that I am working with: clientData.reloadTable( "CreateCSV", "/create/file" ); $("#downloadFrame").attr("src","/download/download"); The first statement in the code above creates a CSV file on the disk. The second statement d ...

Unable to retrieve controller properties within a view using UI router and the 'controller as' syntax

Struggling to correctly access controller object properties in my view while using ui-router for routing with nested scopes. Want to implement 'controller as' syntax but facing syntax issues. app.js (routing setup) (function() { angular ...

Storing props in JSX components using variables in React.jsLearn how to set props in JSX components and

If I have already created a component: class Co extends React.Component { render = () => { const name = this.props.name; return ( <p>Hello, my name is {name}</p> ) } } and stored it in a variable ...

Predict the activity intensity based on the ID and reshape the data accordingly

I am currently working with a dataframe that is structured by timestamp and ID. In this dataframe, I have data for each ID# and minute, with 8 columns of information containing predictions for four different types of activity intensity: Sedentary, Light, ...

Focusing solely on a particular category in EJS

I am struggling with this code snippet. HTML: <header<% if ( current.source === 'features' || current.path[0] === 'index' || current.source !== 'customers' ) { %> class="header-white"<% } %>> <div cl ...

Experiencing an inexplicable blurring effect on the modal window

Introduction - I've implemented a feature where multiple modal windows can be opened on top of each other and closed sequentially. Recently, I added a blur effect that makes the background go blurry when a modal window is open. Subsequently opening an ...

What is the best method for utilizing R's pdftools and stringr to extract the author's name from the initial page of various PDF documents?

My goal is to extract a specific line of text from the first page of each multi-page PDF file within a list of PDFs. I am aiming to store this extracted text in a dataframe so that I can identify the author of each PDF, as the author's name consistent ...

having difficulty choosing a particular identifier from a JSON string

I'm currently working on a project to create an admin page for managing client information. However, I've encountered an issue where I am unable to select the client's unique ID to display all of their information on a separate page. On the ...

Access the data within a jsonArray using Cypress

I'm dealing with a test.json file that contains a jsonArray [{ "EMAIL": "email_1", "FIRST_NAME": "Daniel" }, [{ "EMAIL": "email_2", "FIRST_NAME": "John" }] ] I'm trying to figure out how to use cypre ...

Minimize the count of switch cases that are not empty

How can I optimize the number of cases in my switch statement to align with SonarQube recommendations? Currently, I have 37 cases in a switch statement, but SonarQube recommends only 30. I believe that my code is functioning correctly, and the issue lies ...

Unable to retrieve fields once an array has been added to another array

I am facing an issue with accessing specific fields in an array of sections. The sections are added to the array when a user clicks on a checkbox, and the structure is defined as follows: $scope.print = { sections:[] }; Once all the selected sections ...

Resetting form fields once data has been successfully posted to MongoDB

I have successfully set up a form that sends data to a MongoDB database. However, I am facing an issue with refreshing the input fields after the form is submitted without reloading the entire page. After calling the resetBooks() function, it seems like i ...

The responseText attribute in Ajax seems to be malfunctioning

When running my ajax code, I encountered a problem with the responseText. The PHP script is supposed to return the username of the logged-in user, but it is also echoing out the header of my website along with the username. <DOCTYPE html> <html ...

Tips for passing parameters to a function in an object declaration

I am facing a challenge in my code where I have most of it inside an object literal. There are a few functions where I would like to pass arguments as parameters, but I am struggling to make it work. Here is a snippet of the object structure: var example ...

Sinon threw an assertion error out of the blue

Just diving into using Sinon and facing a small hiccup. Let's say we have a module (named myModule.js) defined as follows: //myModule.js var _f2 = function() { console.log('_f2 enter'); return {prop1:'var1'}; }; var f1 = ...

Passing parameters to a controller method in AngularJS from a directive

Embarking on my Angular JS journey, I have begun creating custom directives for a project. As part of the task, I needed to generate an angular tree and found a code snippet on a plunkr sample by someone else. Although it is not originally my code, I tried ...

Issue with JavaScript causing circles to form around a parent div

I am struggling to position a set of circles around a parent div in my code. I want 6 circles to form a circle around the parent div, but they are not lining up correctly. Can someone help me identify what I'm doing wrong? var div = 360 / 6; var ra ...

Transform the date to match the user's preferred timezone abbreviation

I am currently utilizing the momentJS library for timezone conversion logic within my JavaScript code. I retrieve the User Preference Timezone abbreviation from a web service response, but when attempting to convert the date using the Timezone abbreviation ...

Using `ngRepeat` on a different array of values for repetition

Working with AngularJS. Here is an example of a JSON object: "skills": { "Charisma": {}, "Dexterity": { "Sk3": [ [ true, true, true, true, false ], 44 ] }, ... And the corresponding HTML: <div class="pan ...