### Install shinyjs Package (R) Source: https://github.com/daattali/shinyjs/blob/master/README.md Provides R code to install the shinyjs package from CRAN or GitHub. The CRAN version is stable, while the GitHub version includes the latest development features. ```r install.packages("shinyjs") ``` ```r install.packages("remotes") remotes::install_github("daattali/shinyjs") ``` -------------------------------- ### Complete Shiny Form Example with Validation and Feedback Source: https://context7.com/daattali/shinyjs/llms.txt Demonstrates multiple shinyjs functions used together in a form scenario, including validation, progressive disclosure of fields, and user feedback. This example utilizes inline CSS for styling and various shinyjs functions like `toggle`, `hide`, `show`, `reset`, `toggleState`, and `onclick`. It requires the shiny and shinyjs libraries. ```r library(shiny) library(shinyjs) shinyApp( ui = fluidPage( useShinyjs(), inlineCSS(list( ".error-text" = "color: red; font-size: 0.9em;", ".success-msg" = "color: green; background: #e8f5e9; padding: 15px; border-radius: 5px;" )), titlePanel("Registration Form"), div(id = "formPanel", textInput("email", "Email *", ""), hidden(span(id = "emailError", class = "error-text", "Please enter a valid email")), textInput("name", "Full Name *", ""), a(id = "toggleOptional", "Show optional fields", style = "cursor: pointer; color: blue;"), hidden( div(id = "optionalFields", textInput("company", "Company", ""), textInput("phone", "Phone", "") ) ), br(), disabled(actionButton("submit", "Submit", class = "btn-primary")), actionButton("reset", "Clear Form") ), hidden( div(id = "successPanel", class = "success-msg", h4("Registration Complete!"), p(id = "confirmationText"), actionButton("newForm", "Submit Another") ) ) ), server = function(input, output) { # Toggle optional fields onclick("toggleOptional", { toggle("optionalFields", anim = TRUE) html("toggleOptional", ifelse(input$toggleOptional %% 2 == 1, "Hide optional fields", "Show optional fields")) }) # Email validation observe({ valid_email <- grepl("^[^@]+@[^@]+\\.[^@]+$", input$email) toggle("emailError", condition = nchar(input$email) > 0 && !valid_email) }) # Enable submit when required fields are filled observe({ valid_email <- grepl("^[^@]+@[^@]+\\.[^@]+$", input$email) toggleState("submit", condition = valid_email && nchar(input$name) > 0) }) # Handle form submission observeEvent(input$submit, { hide("formPanel", anim = TRUE, animType = "fade") delay(500, { html("confirmationText", paste("Thank you,", input$name, "! We'll contact you at", input$email)) show("successPanel", anim = TRUE, animType = "fade") }) }) # Reset form observeEvent(input$reset, { reset("formPanel") }) # Start new form observeEvent(input$newForm, { hide("successPanel") reset("formPanel") show("formPanel", anim = TRUE) }) } ) ``` -------------------------------- ### Reload the Page with refresh (R) Source: https://context7.com/daattali/shinyjs/llms.txt The refresh() function reloads the entire Shiny application page, effectively resetting all application state. This is useful for starting over or applying significant changes. Requires shiny and shinyjs libraries. ```r library(shiny) library(shinyjs) shinyApp( ui = fluidPage( useShinyjs(), textInput("data", "Enter some data", ""), actionButton("refresh", "Start over (refresh page)") ), server = function(input, output) { observeEvent(input$refresh, { refresh() }) } ) ``` -------------------------------- ### Initialize shinyjs in a Shiny App UI (R) Source: https://github.com/daattali/shinyjs/blob/master/README.md Demonstrates how to include the shinyjs library in the UI of a Shiny application using `useShinyjs()`. This is a prerequisite for using most shinyjs functions within the app. ```r library(shiny) library(shinyjs) ui <- fluidPage( useShinyjs(), # Include shinyjs actionButton("button", "Click me"), textInput("text", "Text") ) server <- function(input, output) { observeEvent(input$button, { toggle("text") # toggle is a shinyjs function }) } shinyApp(ui, server) ``` -------------------------------- ### Initialize ShinyJS in a Shiny App Source: https://github.com/daattali/shinyjs/blob/master/tests/manual/htmlTemplate-extend-path/template.html Initializes the ShinyJS library in a Shiny application. This function should be called within the UI definition of your Shiny app to enable ShinyJS functionalities. It sets up the necessary JavaScript environment for ShinyJS to interact with R. ```R shinyjs::useShinyjs() ``` -------------------------------- ### Initialize ShinyJS in a Shiny App Source: https://github.com/daattali/shinyjs/blob/master/tests/manual/htmlTemplate-extend-dep/template.html Initializes the ShinyJS library within a Shiny application. This function should be called in the server logic of your Shiny app to enable ShinyJS functionalities. It does not take any arguments. ```r useShinyjs() ``` -------------------------------- ### MathJax Integration for Math Rendering (JavaScript) Source: https://github.com/daattali/shinyjs/blob/master/tests/manual/prerendered/prerendered.html This script dynamically loads the MathJax library to enable the rendering of mathematical equations in a web page. It creates a script element, sets its source to the MathJax CDN, and appends it to the document's head. This ensures that mathematical formulas are displayed correctly using TeX, AMS, and MathML configurations. ```javascript (function () { var script = document.createElement("script"); script.type = "text/javascript"; script.src = "https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"; document.getElementsByTagName("head")[0].appendChild(script); })(); ``` -------------------------------- ### Initialize shinyjs with useShinyjs() in R Source: https://context7.com/daattali/shinyjs/llms.txt The `useShinyjs()` function must be called in the UI of a Shiny app to load the necessary JavaScript bindings and CSS for all shinyjs functions. It's typically placed near the top of the UI definition. ```r library(shiny) library(shinyjs) shinyApp( ui = fluidPage( useShinyjs(), # Initialize shinyjs - required for all shinyjs functions actionButton("btn", "Click me"), textInput("text", "Text input") ), server = function(input, output) { observeEvent(input$btn, { toggle("text") # Now shinyjs functions work }) } ) ``` -------------------------------- ### Run Arbitrary R Code Live in Shiny (R) Source: https://github.com/daattali/shinyjs/blob/master/README.md The `runcode` function from the shinyjs package adds a text input to a Shiny app, allowing users to execute arbitrary R code dynamically. This is useful for interactive debugging or experimentation within the app. ```r # This function is called within the Shiny app's UI or server logic # Example usage would involve integrating it into a Shiny app structure # For instance, by calling runcode() in the UI definition. ``` -------------------------------- ### Shiny Tabset Initialization and Toggling (jQuery) Source: https://github.com/daattali/shinyjs/blob/master/tests/manual/prerendered/prerendered.html This JavaScript code initializes and manages tabset navigation within Shiny applications. It builds tabsets based on 'section-TOC' and implements a dropdown toggle for tab navigation, allowing users to switch between different sections of content. This script executes upon document readiness. ```javascript $(document).ready(function () { window.buildTabsets("section-TOC"); }); $(document).ready(function () { $('.tabset-dropdown > .nav-tabs > li').click(function () { $(this).parent().toggleClass('nav-tabs-open'); }); }); ``` -------------------------------- ### Extend shinyjs with Custom JavaScript Functions (R) Source: https://github.com/daattali/shinyjs/blob/master/README.md The `extendShinyjs` function allows advanced users to define their own JavaScript functions that can be called directly from R. This facilitates complex interactions between R and JavaScript, requiring familiarity with both languages. ```r # This function is called within the Shiny app's server logic # Example: extendShinyjs(text = "function myCustomFunc(arg) { console.log(arg); }", functions = "myCustomFunc") # Then, in the server: myCustomFunc("hello") ``` -------------------------------- ### Display JavaScript Console Logs in R Console (R) Source: https://github.com/daattali/shinyjs/blob/master/README.md The `showLog` function enables the display of JavaScript `console.log()` messages directly in the R console. This simplifies debugging Shiny apps by centralizing log output. ```r # This function is called within the Shiny app's server logic # Example: showLog() # It requires that console.log() messages have been generated in the JavaScript environment. ``` -------------------------------- ### Display Messages with alert and logjs (R) Source: https://context7.com/daattali/shinyjs/llms.txt The alert() function displays a popup message to the user, while logjs() writes messages to the browser's JavaScript console for debugging. showLog() redirects JS console messages to the R console. Requires shiny and shinyjs libraries. ```r library(shiny) library(shinyjs) shinyApp( ui = fluidPage( useShinyjs(), actionButton("showAlert", "Show alert"), actionButton("logMessage", "Log to console"), textInput("text", "Type something") ), server = function(input, output) { showLog() # Enable JS console logging to R console observeEvent(input$showAlert, { alert(paste("You entered:", input$text)) }) observeEvent(input$logMessage, { logjs(paste("Current input value:", input$text)) }) observe({ logjs(paste("Text changed to:", input$text)) }) } ) ``` -------------------------------- ### Shinyjs JavaScript Initialization and Message Handlers Source: https://github.com/daattali/shinyjs/blob/master/tests/manual/prerendered/prerendered.html This snippet initializes the shinyjs JavaScript library with its version and debug status. It also defines custom message handlers for various shinyjs functions (show, hide, enable, disable, toggle, toggleState), allowing Shiny applications to trigger these JavaScript actions from R. It includes debug logging for messages. ```javascript shinyjs.version = '2.1.0.9002'; shinyjs.debug = false; Shiny.addCustomMessageHandler('shinyjs-show', function(params) { shinyjs.debugMessage('shinyjs: calling function \"show\" with parameters:'); shinyjs.debugMessage(params); shinyjs.show(params);}); Shiny.addCustomMessageHandler('shinyjs-hide', function(params) { shinyjs.debugMessage('shinyjs: calling function \"hide\" with parameters:'); shinyjs.debugMessage(params); shinyjs.hide(params);}); Shiny.addCustomMessageHandler('shinyjs-toggle', function(params) { shinyjs.debugMessage('shinyjs: calling function \"toggle\" with parameters:'); shinyjs.debugMessage(params); shinyjs.toggle(params);}); Shiny.addCustomMessageHandler('shinyjs-enable', function(params) { shinyjs.debugMessage('shinyjs: calling function \"enable\" with parameters:'); shinyjs.debugMessage(params); shinyjs.enable(params);}); Shiny.addCustomMessageHandler('shinyjs-disable', function(params) { shinyjs.debugMessage('shinyjs: calling function \"disable\" with parameters:'); shinyjs.debugMessage(params); shinyjs.disable(params);}); Shiny.addCustomMessageHandler('shinyjs-toggleState', function(params) { shinyjs.debugMessage('shinyjs: calling function \"toggleState\" with parameters:'); shinyjs.debugMessage(params); shinyjs.toggleState(params);}); Shiny.add ``` -------------------------------- ### Extend ShinyJS with Custom Functions Source: https://github.com/daattali/shinyjs/blob/master/tests/manual/htmlTemplate-extend-path/template.html Extends ShinyJS with custom JavaScript functions. This allows you to define and use your own JavaScript logic within your Shiny application, making it accessible from R. The `script` argument specifies the path to your custom JavaScript file, and `functions` lists the functions to expose. ```R shinyjs::extendShinyjs(script = script, functions = "pageCol") ``` -------------------------------- ### Run R Code on User Events with onclick and onevent (R) Source: https://context7.com/daattali/shinyjs/llms.txt The onclick() function executes R code upon an element click, while onevent() supports various event types (hover, keypress, mouse events). Both can receive event properties as arguments. Requires the shiny and shinyjs libraries. ```r library(shiny) library(shinyjs) shinyApp( ui = fluidPage( useShinyjs(), p(id = "clickMe", style = "cursor: pointer;", "Click me to see the date"), p(id = "hoverZone", style = "background: #eee; padding: 20px;", "Hover here to show/hide the message below"), p(id = "message", "I appear on hover!"), p(id = "keyInfo", "Click here and press any key"), p(id = "keyDisplay", "Key info will appear here") ), server = function(input, output) { # Simple onclick onclick("clickMe", alert(paste("Today is", Sys.Date()))) # Mouse enter/leave events onevent("mouseenter", "hoverZone", show("message")) onevent("mouseleave", "hoverZone", hide("message")) # Keyboard event with properties callback onevent("keypress", "keyInfo", function(event) { html("keyDisplay", paste("Key:", event$key, "| Code:", event$which)) }) } ) ``` -------------------------------- ### Run Arbitrary R Code Interactively (Development Only) Source: https://context7.com/daattali/shinyjs/llms.txt Adds a text input to your Shiny app for running arbitrary R code. This function is intended for development purposes only and should not be included in production applications. It requires the shiny and shinyjs libraries. ```r library(shiny) library(shinyjs) shinyApp( ui = fluidPage( useShinyjs(), h4("Development console - run any R code:"), runcode(code = "shinyjs::alert('Hello!')"), hr(), p(id = "demo", "This paragraph can be manipulated"), textInput("myInput", "A test input", "initial value") ), server = function(input, output) {} ) # Try running: shinyjs::hide("demo") # Or: shinyjs::reset("myInput") ``` -------------------------------- ### Execute Arbitrary JavaScript with runjs (R) Source: https://context7.com/daattali/shinyjs/llms.txt The runjs() function allows direct execution of arbitrary JavaScript code within a Shiny application. It should be used sparingly when built-in functions are insufficient. Requires shiny and shinyjs libraries. ```r library(shiny) library(shinyjs) shinyApp( ui = fluidPage( useShinyjs(), actionButton("scrollTop", "Scroll to top"), actionButton("showDate", "Show JS date"), div(style = "height: 2000px;", "Scroll down and click 'Scroll to top'") ), server = function(input, output) { observeEvent(input$scrollTop, { runjs("window.scrollTo(0, 0);") }) observeEvent(input$showDate, { runjs("alert('JavaScript says: ' + new Date().toLocaleString());") }) } ) ``` -------------------------------- ### Initialize Elements as Invisible with hidden() in R Source: https://context7.com/daattali/shinyjs/llms.txt The `hidden()` function in shinyjs wraps Shiny tags to ensure they are invisible when the application initially loads. These elements can be revealed later using `show()` or `toggle()`, facilitating progressive disclosure patterns. ```r library(shiny) library(shinyjs) shinyApp( ui = fluidPage( useShinyjs(), actionButton("showAdvanced", "Show advanced options"), hidden( div(id = "advancedPanel", h4("Advanced Settings"), numericInput("threshold", "Threshold", 0.5), checkboxInput("debug", "Enable debug mode", FALSE) ) ) ), server = function(input, output) { observeEvent(input$showAdvanced, { show("advancedPanel", anim = TRUE, animType = "slide") }) } ) ``` -------------------------------- ### Disable UI Elements with ShinyJS Source: https://github.com/daattali/shinyjs/blob/master/tests/manual/htmlTemplate/template.html Demonstrates how to disable specific UI elements within a Shiny application using the `disabled()` function from the shinyjs package. This is useful for controlling user interaction based on application state. ```r library(shiny) library(shinyjs) ui <- fluidPage( useShinyjs(), disabled(actionButton("disabled", "This is disabled")) ) server <- function(input, output, session) { # ... server logic ... } ``` -------------------------------- ### Log Messages to JavaScript Console (R) Source: https://github.com/daattali/shinyjs/blob/master/README.md The `logjs` function allows R code to send messages to the browser's JavaScript console. This is primarily used for debugging purposes during Shiny app development. ```r # This function is called within the Shiny app's server logic # Example: logjs("User clicked the button") # The message will appear in the browser's developer console. ``` -------------------------------- ### Programmatically Click a Button with shinyjs click() Source: https://context7.com/daattali/shinyjs/llms.txt The click() function in shinyjs simulates a user clicking an action button in a Shiny application. This is useful for automating button actions or creating interfaces that advance automatically. It takes the ID of the action button to be clicked as an argument. ```r library(shiny) library(shinyjs) shinyApp( ui = fluidPage( useShinyjs(), p("Counter: ", textOutput("count", inline = TRUE)), actionButton("increment", "Increment"), p("The button auto-clicks every 2 seconds") ), server = function(input, output) { output$count <- renderText({ input$increment }) observe({ invalidateLater(2000) click("increment") }) } ) ``` -------------------------------- ### Add Inline CSS to Shiny App (R) Source: https://github.com/daattali/shinyjs/blob/master/README.md The `inlineCSS` function provides a convenient way to inject inline CSS rules directly into a Shiny application's HTML. This allows for easy styling of specific elements without needing separate CSS files. ```r # This function is called within the Shiny app's UI definition # Example: inlineCSS("#myElement { color: blue; }") ``` -------------------------------- ### Extend ShinyJS with Custom Functions Source: https://github.com/daattali/shinyjs/blob/master/tests/manual/htmlTemplate-extend-text/template.html Extends ShinyJS with custom JavaScript functions. This allows you to define and use your own JavaScript logic within Shiny. The 'jscode' variable should contain your JavaScript code, and 'functions' specifies the names of the functions to expose. ```R extendShinyjs(text = jscode, functions = "pageCol") ``` -------------------------------- ### Bootstrap Styling for Pandoc Tables (jQuery) Source: https://github.com/daattali/shinyjs/blob/master/tests/manual/prerendered/prerendered.html This JavaScript code applies Bootstrap table classes to tables generated by Pandoc. It targets odd-numbered rows within the table body to add the 'table table-condensed' classes, enhancing their appearance. This script is intended to be run when the document is ready. ```javascript function bootstrapStylePandocTables() { $('tr.odd').parent('tbody').parent('table').addClass('table table-condensed'); } $(document).ready(function () { bootstrapStylePandocTables(); }); ``` -------------------------------- ### Add Inline CSS Styles with inlineCSS (R) Source: https://context7.com/daattali/shinyjs/llms.txt The inlineCSS() function applies CSS styles directly to a Shiny application. It accepts either a string of CSS rules or a named list where keys are selectors and values are style declarations. Requires shiny and shinyjs libraries. ```r library(shiny) library(shinyjs) shinyApp( ui = fluidPage( useShinyjs(), # Method 1: CSS string inlineCSS("#title { color: navy; font-size: 2em; }"), # Method 2: Named list inlineCSS(list( ".warning" = "color: orange; border: 1px solid orange; padding: 10px;", ".success" = c("color: green", "background: #e8f5e9", "padding: 10px"), "button" = "margin: 5px;" )), h1(id = "title", "Styled Title"), p(class = "warning", "This is a warning message"), p(class = "success", "This is a success message"), actionButton("btn1", "Button 1"), actionButton("btn2", "Button 2") ), server = function(input, output) {} ) ``` -------------------------------- ### Toggle Element with ShinyJS Source: https://github.com/daattali/shinyjs/blob/master/tests/manual/prerendered/prerendered.html This R code snippet demonstrates how to toggle the visibility of an HTML element with the ID 'square' using the shinyjs package. It observes changes in an input element named 'toggle' and updates an output element 'square' with the square of an input number 'num'. ```R observeEvent(input$toggle, { shinyjs::toggle("square") }) output$square <- renderText({ input$num ^ 2 }) ``` -------------------------------- ### Extend ShinyJS with Custom JavaScript Functions Source: https://context7.com/daattali/shinyjs/llms.txt Define custom JavaScript functions that can be called from R using the js$ object. This is useful for advanced users needing functionality beyond the built-in functions. It requires the shiny and shinyjs libraries. ```r library(shiny) library(shinyjs) jsCode <- " shinyjs.backgroundCol = function(params) { var defaultParams = { id : null, col : 'red' }; params = shinyjs.getParams(params, defaultParams); $('#' + params.id).css('background-color', params.col); } shinyjs.init = function() { console.log('shinyjs initialized!'); } " shinyApp( ui = fluidPage( useShinyjs(), extendShinyjs(text = jsCode, functions = c("backgroundCol")), selectInput("color", "Choose color", c("red", "blue", "green", "yellow")), actionButton("apply", "Apply color"), p(id = "target", style = "padding: 20px;", "This paragraph will change color") ), server = function(input, output) { observeEvent(input$apply, { js$backgroundCol(id = "target", col = input$color) }) } ) ``` -------------------------------- ### Control Element Visibility with show, hide, toggle in R Source: https://context7.com/daattali/shinyjs/llms.txt These R functions control the visibility of HTML elements in Shiny apps. `show()` makes elements visible, `hide()` makes them invisible, and `toggle()` switches between states. Animations can be applied, and `toggle()` supports conditional visibility via the `condition` parameter. ```r library(shiny) library(shinyjs) shinyApp( ui = fluidPage( useShinyjs(), checkboxInput("showText", "Show the text", TRUE), actionButton("toggleBtn", "Toggle visibility"), p(id = "myText", "This text can be shown or hidden"), p(id = "animatedText", "This will fade in/out") ), server = function(input, output) { # Conditional visibility based on checkbox observe({ toggle(id = "myText", condition = input$showText) }) # Toggle with fade animation on button click observeEvent(input$toggleBtn, { toggle("animatedText", anim = TRUE, animType = "fade", time = 0.5) }) # Direct show/hide examples: # show("myText") # hide("myText") # hide("myText", anim = TRUE, animType = "slide", time = 1) } ) ``` -------------------------------- ### ShinyJS JavaScript Event and Utility Handlers Source: https://github.com/daattali/shinyjs/blob/master/tests/manual/prerendered/prerendered.html This group of handlers manages client-side events and utility functions within Shiny. It includes handlers for one-time events, removing events, displaying alerts, logging messages to the browser console, running arbitrary JavaScript code, resetting ShinyJS state, delaying execution, and refreshing the page. These rely on the Shiny JavaScript library. ```javascript Shiny.addCustomMessageHandler('shinyjs-onevent', function(params) { shinyjs.debugMessage('shinyjs: calling function \"onevent\" with parameters:'); shinyjs.debugMessage(params); shinyjs.onevent(params);}); Shiny.addCustomMessageHandler('shinyjs-removeEvent', function(params) { shinyjs.debugMessage('shinyjs: calling function \"removeEvent\" with parameters:'); shinyjs.debugMessage(params); shinyjs.removeEvent(params);}); Shiny.addCustomMessageHandler('shinyjs-alert', function(params) { shinyjs.debugMessage('shinyjs: calling function \"alert\" with parameters:'); shinyjs.debugMessage(params); shinyjs.alert(params);}); Shiny.addCustomMessageHandler('shinyjs-logjs', function(params) { shinyjs.debugMessage('shinyjs: calling function \"logjs\" with parameters:'); shinyjs.debugMessage(params); shinyjs.logjs(params);}); Shiny.addCustomMessageHandler('shinyjs-runjs', function(params) { shinyjs.debugMessage('shinyjs: calling function \"runjs\" with parameters:'); shinyjs.debugMessage(params); shinyjs.runjs(params);}); Shiny.addCustomMessageHandler('shinyjs-reset', function(params) { shinyjs.debugMessage('shinyjs: calling function \"reset\" with parameters:'); shinyjs.debugMessage(params); shinyjs.reset(params);}); Shiny.addCustomMessageHandler('shinyjs-delay', function(params) { shinyjs.debugMessage('shinyjs: calling function \"delay\" with parameters:'); shinyjs.debugMessage(params); shinyjs.delay(params);}); Shiny.addCustomMessageHandler('shinyjs-refresh', function(params) { shinyjs.debugMessage('shinyjs: calling function \"refresh\" with parameters:'); shinyjs.debugMessage(params); shinyjs.refresh(params);}); ``` -------------------------------- ### Initialize Inputs as Disabled with disabled() in R Source: https://context7.com/daattali/shinyjs/llms.txt The `disabled()` function wraps Shiny input elements to make them non-interactive upon initial app load. These inputs can be subsequently enabled using `enable()` or `toggleState()`, allowing for controlled user input. ```r library(shiny) library(shinyjs) shinyApp( ui = fluidPage( useShinyjs(), checkboxInput("agree", "I agree to the terms", FALSE), disabled( actionButton("continue", "Continue") ) ), server = function(input, output) { observe({ toggleState("continue", condition = input$agree) }) } ) ``` -------------------------------- ### Manage CSS Classes with shinyjs addClass, removeClass, toggleClass Source: https://context7.com/daattali/shinyjs/llms.txt shinyjs provides addClass(), removeClass(), and toggleClass() functions to dynamically manage CSS classes on HTML elements. These functions, when used with inlineCSS(), allow for sophisticated dynamic styling within Shiny apps without direct JavaScript manipulation. They are essential for creating interactive and visually responsive user interfaces. ```r library(shiny) library(shinyjs) shinyApp( ui = fluidPage( useShinyjs(), inlineCSS(list( ".highlighted" = "background-color: yellow; padding: 10px;", ".error" = "color: red; font-weight: bold;", ".large" = "font-size: 1.5em;" )), checkboxInput("highlight", "Highlight text", FALSE), checkboxInput("showError", "Show as error", FALSE), p(id = "myText", "This text can be styled dynamically") ), server = function(input, output) { observe({ toggleClass("myText", "highlighted", input$highlight) toggleClass("myText", "error", input$showError) }) # Direct addClass/removeClass examples: # addClass("myText", "large") # removeClass("myText", "large") } ) ``` -------------------------------- ### Control Input States with enable, disable, toggleState in R Source: https://context7.com/daattali/shinyjs/llms.txt These R functions manage the interactive state of Shiny input elements. `enable()` makes an input usable, `disable()` prevents user interaction, and `toggleState()` conditionally enables or disables inputs, which is useful for form validation. ```r library(shiny) library(shinyjs) shinyApp( ui = fluidPage( useShinyjs(), textInput("email", "Email address", ""), textInput("name", "Full name", ""), actionButton("submit", "Submit") ), server = function(input, output) { # Enable submit button only when both fields have content observe({ toggleState( id = "submit", condition = nchar(input$email) > 0 && nchar(input$name) > 0 ) }) # Alternative: direct enable/disable # disable("submit") # enable("submit") } ) ``` -------------------------------- ### Reset Inputs to Original Values with shinyjs reset() Source: https://context7.com/daattali/shinyjs/llms.txt The reset() function in shinyjs allows for resetting input elements to their initial values. It can target a single input by ID, all inputs within a specified container, or all inputs on the entire page. This is useful for clearing forms or resetting application states. ```r library(shiny) library(shinyjs) shinyApp( ui = fluidPage( useShinyjs(), div(id = "formContainer", textInput("name", "Name", "John"), numericInput("age", "Age", 25), selectInput("color", "Favorite color", c("Red", "Blue", "Green")), radioButtons("size", "Size", c("Small", "Medium", "Large")) ), actionButton("resetName", "Reset name only"), actionButton("resetForm", "Reset entire form"), actionButton("resetAll", "Reset all inputs on page") ), server = function(input, output) { observeEvent(input$resetName, { reset("name") # Reset single input }) observeEvent(input$resetForm, { reset("formContainer") # Reset all inputs in container }) observeEvent(input$resetAll, { reset() # Reset all inputs on page }) } ) ``` -------------------------------- ### ShinyJS JavaScript DOM Manipulation Handlers Source: https://github.com/daattali/shinyjs/blob/master/tests/manual/prerendered/prerendered.html These handlers facilitate direct manipulation of the Document Object Model (DOM) in a Shiny application. They allow R to add/remove CSS classes, toggle classes, set HTML content, and trigger clicks on elements. Dependencies include the Shiny JavaScript library. ```javascript Shiny.addCustomMessageHandler('shinyjs-addClass', function(params) { shinyjs.debugMessage('shinyjs: calling function \"addClass\" with parameters:'); shinyjs.debugMessage(params); shinyjs.addClass(params);}); Shiny.addCustomMessageHandler('shinyjs-removeClass', function(params) { shinyjs.debugMessage('shinyjs: calling function \"removeClass\" with parameters:'); shinyjs.debugMessage(params); shinyjs.removeClass(params);}); Shiny.addCustomMessageHandler('shinyjs-toggleClass', function(params) { shinyjs.debugMessage('shinyjs: calling function \"toggleClass\" with parameters:'); shinyjs.debugMessage(params); shinyjs.toggleClass(params);}); Shiny.addCustomMessageHandler('shinyjs-html', function(params) { shinyjs.debugMessage('shinyjs: calling function \"html\" with parameters:'); shinyjs.debugMessage(params); shinyjs.html(params);}); Shiny.addCustomMessageHandler('shinyjs-click', function(params) { shinyjs.debugMessage('shinyjs: calling function \"click\" with parameters:'); shinyjs.debugMessage(params); shinyjs.click(params);}); ``` -------------------------------- ### Execute Code After a Time Delay with shinyjs delay() Source: https://context7.com/daattali/shinyjs/llms.txt The delay() function from shinyjs executes R code after a specified delay in milliseconds. This is particularly useful for implementing temporary messages, auto-hiding elements, or any functionality that requires timed execution. It takes the delay duration and the code to execute as arguments. ```r library(shiny) library(shinyjs) shinyApp( ui = fluidPage( useShinyjs(), actionButton("save", "Save"), hidden(div(id = "savedMsg", style = "color: green;", "Saved successfully!")) ), server = function(input, output) { observeEvent(input$save, { show("savedMsg") delay(3000, hide("savedMsg", anim = TRUE, animType = "fade")) }) } ) ``` -------------------------------- ### Disable UI Elements with ShinyJS Source: https://github.com/daattali/shinyjs/blob/master/tests/manual/htmlTemplate-extend-path/template.html Disables a UI element using ShinyJS. This function takes an action button as input and returns a modified version of it that is disabled. This is useful for controlling user interaction based on application state. ```R shinyjs::disabled(actionButton("disabled", "this is disabled")) ``` -------------------------------- ### Change Element Content with shinyjs html() Source: https://context7.com/daattali/shinyjs/llms.txt The html() function in shinyjs allows modification of an element's text or HTML content. Content can be entirely replaced or appended to existing content by setting the `add` parameter to TRUE. This function is versatile for updating dynamic content within a Shiny UI. ```r library(shiny) library(shinyjs) shinyApp( ui = fluidPage( useShinyjs(), actionButton("updateTime", "Update timestamp"), actionButton("appendLog", "Add log entry"), p("Current time: ", span(id = "timestamp", "Not updated yet")), div(id = "logArea", "Log entries:") ), server = function(input, output) { observeEvent(input$updateTime, { html("timestamp", as.character(Sys.time())) }) observeEvent(input$appendLog, { html("logArea", paste("
Entry at", Sys.time()), add = TRUE) }) } ) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.