Advanced JS Hooks & Events
Source:vignettes/advanced-js-hooks-and-events.Rmd
advanced-js-hooks-and-events.Rmd
- Inject custom JavaScript to extend SurveyJS far beyond R defaults.
- Validate, log, or react to user input with powerful event hooks.
- Write only the body of your JavaScript function, as a string—see runnable examples below.
- Tip: Always use just the function body (no
function(...) {}
wrapper), and check the browser’s JS console for errors. - For survey building blocks and theming, see the other vignettes.
Table of Contents
- What are JS Hooks?
- Pre-Render Hook
- Post-Render Hook
- Complete Hook
- Custom Event Listeners
- Debugging and Tips
- Further Reference
What are JS Hooks?
- Hooks let you insert custom JavaScript at key points in the survey lifecycle.
- Write just the function body (as a string), not a
full
function() { ... }
. - Hooks run in the browser. Use
console.log()
for debugging.
Pre-Render Hook
Runs before the survey is displayed.
Use for custom validation, event listeners, or setup logic.
Example: Enforce minimum nickname length
surveyjs(
schema = list(
title = "Nickname Check",
questions = list(
list(type = "text", name = "nickname", title = "Enter a nickname")
)
),
pre_render_hook = "
survey.onValidateQuestion.add(function(sender, options) {
if (options.name === 'nickname' && options.value.length < 4) {
options.error = 'Too short';
}
});
"
)
Complete Hook
Runs when the survey is completed by the user.
Use to trigger alerts, send data, or fire custom analytics.
Custom Event Listeners
Attach any SurveyJS event in a pre-render hook.
Example: Log every value change
surveyjs(
schema = list(
title = "Value Tracking",
questions = list(
list(type = "text", name = "email", title = "Your email?")
)
),
pre_render_hook = "
survey.onValueChanged.add(function(sender, options) {
console.log('Field changed:', options.name, options.value);
});
"
)
Debugging and Tips
- Write only the function body (not
function() { ... }
). - Use
console.log()
for debugging in your browser’s JS console. - If your JS code errors, check the browser console for details.
- See all events: SurveyJS Events Reference.
Note:
Custom JS hooks are for advanced use and are executed directly in the browser. In public or multi-user apps, only use this feature with users you fully trust.
To allow JS hooks only for trusted users, use a pattern like: