var jsPsych = initJsPsych(settings);| Parameter | Type | Description |
|---|---|---|
| settings | object | The settings object for initializing jsPsych. See table below. |
The settings object can contain several parameters. None of the parameters are required.
| Parameter | Type | Description |
|---|---|---|
| display_element | string | The ID of an HTML element to display the experiment in. If left blank, jsPsych will use the <body> element to display content. All keyboard event listeners are bound to this element. In order for a keyboard event to be detected, this element must have focus (be the last thing that the participant clicked on). |
| on_finish | function | Function to execute when the experiment ends. |
| on_trial_start | function | Function to execute when a new trial begins. |
| on_trial_finish | function | Function to execute when a trial ends. |
| on_data_update | function | Function to execute every time data is stored using the jsPsych.data.write method. All plugins use this method to save data (via a call to jsPsych.finishTrial, so this function runs every time a plugin stores new data. |
| on_interaction_data_update | function | Function to execute every time a new interaction event occurs. Interaction events include clicking on a different window (blur), returning to the experiment window (focus), entering full screen mode (fullscreenenter), and exiting full screen mode (fullscreenexit). |
| on_close | function | Function to execute when the user leaves the page. Can be used, for example, to save data before the page is closed. |
| show_progress_bar | boolean | If true, then a progress bar is shown at the top of the page. Default is false. |
| message_progress_bar | string or function | Message to display next to the progress bar or a function that returns that message. The default is 'Completion Progress'. If message_progress_bar is a function, it receives one single argument which is the current progress, ranging from 0 to 1; the function gets called on every progress bar update automatically. |
| auto_update_progress_bar | boolean | If true, then the progress bar at the top of the page will automatically update as every top-level timeline or trial is completed. |
| use_webaudio | boolean | If false, then jsPsych will not attempt to use the WebAudio API for audio playback. Instead, HTML5 Audio objects will be used. The WebAudio API offers more precise control over the timing of audio events, and should be used when possible. The default value is true. |
| default_iti | numeric | The default inter-trial interval in ms. The default value if none is specified is 0ms. |
| experiment_width | numeric | The desired width of the jsPsych container in pixels. If left undefined, the width will be 100% of the display element. Usually this is the <body> element, and the width will be 100% of the screen size. |
| minimum_valid_rt | numeric | The minimum valid response time for key presses during the experiment. Any key press response time that is less than this value will be treated as invalid and ignored. Note that this parameter only applies to keyboard responses, and not to other response types such as buttons and sliders. The default value is 0. |
| override_safe_mode | boolean | Running a jsPsych experiment directly in a web browser (e.g., by double clicking on a local HTML file) will load the page using the file:// protocol. Some features of jsPsych don't work with this protocol. By default, when jsPsych detects that it's running on a page loaded via the file:// protocol, it runs in safe mode, which automatically disables features that don't work in this context. Specifically, the use of Web Audio is disabled (audio will be played using HTML5 audio instead, even if use_webaudio is true) and video preloading is disabled. The override_safe_mode parameter defaults to false, but you can set it to true to force these features to operate under the file:// protocol. In order for this to work, you will need to disable web security (CORS) features in your browser - this is safe to do if you know what you are doing. Note that this parameter has no effect when you are running the experiment on a web server, because the page will be loaded via the http:// or https:// protocol. |
| case_sensitive_responses | boolean | If true, then jsPsych will make a distinction between uppercase and lowercase keys when evaluating keyboard responses, e.g. "A" (uppercase) will not be recognized as a valid response if the trial only accepts "a" (lowercase). If false, then jsPsych will not make a distinction between uppercase and lowercase keyboard responses, e.g. both "a" and "A" responses will be valid when the trial's key choice parameter is "a". Setting this parameter to false is useful if you want key responses to be treated the same way when CapsLock is turned on or the Shift key is held down. The default value is false. |
| extensions | array | Array containing information about one or more jsPsych extensions that are used during the experiment. Each extension should be specified as an object with type (required), which is the name of the extension, and params (optional), which is an object containing any parameter-value pairs to be passed to the extension's initialize function. Default value is an empty array. |
| record_session | boolean | object | If true, jsPsych captures a high-fidelity recording of the session — DOM mutations within the display element, mouse/touch/keyboard/clipboard input, scroll position (window and per-element), video and audio playback events, viewport changes (including pinch zoom), and every Math.random() output — sufficient to reconstruct a replay of what the participant saw and did. The recording is retrieved at the end of the experiment via jsPsych.getSessionRecording() and can be JSON.stringify'd and saved alongside the trial data. While enabled, Math.random is wrapped to log every call into the recording; this is reverted when the experiment ends. The default value is false. Pass an object instead of true to opt out of categories or bound memory: capture_inputs (default true; set false for surveys whose responses must not be retained verbatim), capture_canvas (default true; set false to skip canvas pixel snapshots), capture_random (default true; set false when the RNG is called millions of times and reproducibility isn't needed), and max_events (default unlimited; when exceeded, recording stops with end_reason: "memory_limit"). Note: with capture_inputs: true, text typed into form inputs (e.g. survey responses) is captured verbatim. Inform participants accordingly. |
Returns a jsPsych instance, which all jsPsych methods on this page are called on. Therefore it is not possible to call any of the jsPsych methods listed on this page until this initJsPsych function is called and a jsPsych instance is created.
This function initializes jsPsych with the specified experiment settings.
var jsPsych = initJsPsych({
on_finish: function() {
jsPsych.data.displayData();
},
show_progress_bar: true,
default_iti: 500
});For more examples, see the HTML files in the examples folder.
jsPsych.abortCurrentTimeline()None.
None.
Ends the current timeline. If timelines are nested, then only the timeline that contains the current trial is ended.
var jsPsych = initJsPsych({
on_finish: function() {
jsPsych.data.displayData();
}
});
var images = [
"img/1.gif", "img/2.gif", "img/3.gif", "img/4.gif",
"img/5.gif", "img/6.gif", "img/7.gif", "img/8.gif",
"img/9.gif", "img/10.gif"
];
var trials = [];
for (var i = 0; i < images.length; i++) {
trials.push({
stimulus: images[i]
});
}
var block = {
type: jsPsychImageKeyboardResponse,
choices: ['y', 'n'],
prompt: '<p>Press "y" to Continue. Press "n" to end this node of the experiment.</p>',
on_finish: function(data) {
if (jsPsych.pluginAPI.compareKeys(data.response, 'n')) {
jsPsych.abortCurrentTimeline();
}
},
timeline: trials
}
var after_block = {
type: jsPsychHtmlKeyboardResponse,
stimulus: '<p>The next node</p>'
}
jsPsych.run([block, after_block]);jsPsych.abortExperiment(message, data)| Parameter | Type | Description |
|---|---|---|
| message | string | A message to display on the screen after the experiment is over. Can include HTML formatting. |
| data | object | An optional object of key-value pairs to store as data in the final trial of the experiment. |
None.
Ends the experiment, skipping all remaining trials. If the on_finish event handler for jsPsych returns a Promise then the message will not be displayed until the promise is resolved.
var trial = {
type: jsPsychImageKeyboardResponse,
stimulus: 'image1.jpg',
choices: ['y', 'n'],
prompt: '<p>Press "y" to Continue. Press "n" to end the experiment</p>',
on_finish: function(data){
if(jsPsych.pluginAPI.compareKeys(data.response, "n")){
jsPsych.abortExperiment('The experiment was ended by pressing "n".');
}
}
}jsPsych.abortTimelineByName()| Parameter | Type | Description |
|---|---|---|
| name | string | The name of the timeline to abort. |
None.
Ends the currently active timeline that matches the name parameter. This can be used to control which level is aborted in a nested timeline structure.
const fixation = {
type: jsPsychHtmlKeyboardResponse,
stimulus: '<p>+</p>',
choices: "NO_KEYS",
trial_duration: 1000
}
const test = {
type: jsPsychImageKeyboardResponse,
stimulus: jsPsych.timelineVariable('stimulus'),
choices: ['y', 'n'],
on_finish: function(data){
if(jsPsych.pluginAPI.compareKeys(data.response, "n")){
jsPsych.abortTimelineByName('memory_test');
}
}
}
const memoryResponseProcedure = {
timeline: [fixation, test]
}
// the variable `encode` is not shown, but imagine a trial that displays
// some stimulus to remember.
const memoryEncodeProcedure = {
timeline: [fixation, encode]
}
const memoryTestProcedure = {
timeline: [memoryEncodeProcedure, memoryResponseProcedure]
name: 'memory_test',
timeline_variables: [
{stimulus: 'image1.png'},
{stimulus: 'image2.png'},
{stimulus: 'image3.png'},
{stimulus: 'image4.png'}
]
}
jsPsych.evaluateTimelineVariable(variable_name)| Parameter | Type | Description |
|---|---|---|
| variable_name | string | The name of the variable to evaluate. |
Returns the current value of the corresponding timeline variable.
Unlike jsPsych.timelineVariable(), evaluateTimelineVariable() immediately returns the current value of the timeline variable.
It should be used whenever you are in a context where immediate evaluation is appropriate. For example, if you referencing a
timeline variable within a function, immediate evaluation is usually correct.
const trial = {
type: jsPsychHtmlKeyboardResponse,
stimulus: function(){
return `<img style='width:100px; height:100px;' src='${jsPsych.evaluateTimelineVariable('image')}'></img>`;
}
}
const procedure = {
timeline: [trial],
timeline_variables: [
{image: 'face1.png'},
{image: 'face2.png'},
{image: 'face3.png'},
{image: 'face4.png'}
]
}jsPsych.finishTrial(data)| Parameter | Type | Description |
|---|---|---|
| data | object | The data to store for the trial. |
Returns nothing.
This method tells jsPsych that the current trial is over. It is used in all of the plugins to end the current trial. When the trial ends, a few things happen:
- The data is stored using
jsPsych.data.write() - The
on_finishcallback function is executed for the trial - The
on_trial_finishcallback function is executed - The display element is cleared, and any timeouts that are pending are cleared.
- The progress bar is updated if it is being displayed
- The experiment ends if the trial is the last one (and the
on_finishcallback function is executed). - The next trial, if one exists, is started.
// this code would be in a plugin
jsPsych.finishTrial({correct_response: true});jsPsych.getCitations(plugins, format)| Parameter | Type | Description |
|---|---|---|
| plugins | array | Array containing list of plugins/extensions by name. |
| format | string | Output citation format ("apa" |
String of generated citations in the specified format for the jsPsych library, followed by that for each input plugin/extension, separated with a "\n" character.
Get citations in a specified format for the jsPsych library and input list of plugins/extensions, usually those used within an experiment.
// in browser console
jsPsych.getCitations() // prints citation for jsPsych library in APA format
jsPsych.getCitations([TestPlugin], "bibtex") // prints citation for jsPsych library and TestPlugin (if different) in BibTex formatjsPsych.getCurrentTrial()None.
Returns the object describing the current trial. The object will contain all of the parameters associated with the current trial.
Get a description of the current trial.
var trial = jsPsych.getCurrentTrial();
console.log('The current trial is using the '+trial.type+' plugin');jsPsych.getDisplayElement()None.
Returns the HTML DOM element used for displaying the experiment.
Get the DOM element that displays the experiment.
var el = jsPsych.getDisplayElement();
// hide the jsPsych display
el.style.visibility = 'hidden';jsPsych.getInitSettings()None
Returns the settings object used to initialize the experiment.
Gets the object containing the settings for the current experiment.
var settings = jsPsych.getInitSettings();
// check the experiment structure
console.log(JSON.stringify(settings.timeline));jsPsych.getProgress()None.
Returns an object with the following properties:
| Property | Type | Description |
|---|---|---|
| total_trials | numeric | Indicates the number of trials in the experiment. Note that this does not count possible loops or skipped trials due to conditional statements. |
| current_trial_global | numeric | Returns the trial index of the current trial in a global scope. Every trial will increase this count by 1. |
| percent_complete | numeric | Estimates the percent of the experiment that is complete. Works as expected for experiments without conditional or looping timelines. For complex timelines, the percent is an approximation. |
This method returns information about the length of the experiment and the participant's current location in the experiment timeline.
var progress = jsPsych.getProgress();
alert('You have completed approximately '+progress.percent_complete+'% of the experiment');jsPsych.getSessionRecording()None.
Returns a SessionRecording object when the experiment was initialized with record_session: true, or undefined otherwise. The object is JSON-serializable.
Returns the high-fidelity session recording produced by the record_session option. The recording includes the rendered DOM at the start of every trial, all DOM mutations within #jspsych-content, mouse, touch, keyboard, and clipboard events, scroll position (window and per-element), video and audio playback events, viewport changes, and every Math.random() output. The returned object is versioned (schema_version: 1); see Session Recording Schema for the full format reference.
var jsPsych = initJsPsych({
record_session: true,
on_finish: function() {
var recording = jsPsych.getSessionRecording();
var blob = new Blob([JSON.stringify(recording)], { type: "application/json" });
// ...persist or upload `blob` alongside the trial data
}
});jsPsych.getStartTime()None.
Returns a Date object indicating when the experiment began.
Get the time that the experiment began.
var start_time = jsPsych.getStartTime();jsPsych.getTotalTime()None.
Returns a numeric value indicating the number of milliseconds since jsPsych.run was called.
Gets the total time the participant has been in the experiment.
var time = jsPsych.getTotalTime();
console.log(time);jsPsych.pauseExperiment()None.
None.
Pauses the experiment. The experiment will finish the current trial, but will not execute any additional trials until jsPsych.resumeExperiment() is called.
var trial = {
type: jsPsychHtmlKeyboardResponse,
stimulus: 'Press p to take a 30 second break. Otherwise, press c to continue immediately.',
choices: ['p', 'c'],
on_finish: function(data){
if (jsPsych.pluginAPI.compareKeys(data.response, "p")) {
jsPsych.pauseExperiment();
setTimeout(jsPsych.resumeExperiment, 30000);
}
}
}jsPsych.resumeExperiment()None.
None.
Resumes the experiment after a call to jsPsych.pauseExperiment(). If the post trial delay (post_trial_gap) has not yet been reached, then the experiment will not continue until the delay is finished. For example, if post_trial_gap was 10,000ms and jsPsych.resumeExperiment() was called 6,000ms after the previous trial finished, then the experiment would not continue for another 4,000ms.
var trial = {
type: jsPsychHtmlKeyboardResponse,
stimulus: 'Press p to take a 30 second break. Otherwise, press c to continue immediately.',
choices: ['p','c'],
on_finish: function(data){
if(jsPsych.pluginAPI.compareKeys(data.response, "p")) {
jsPsych.pauseExperiment();
setTimeout(jsPsych.resumeExperiment, 30000);
}
}
}jsPsych.run(timeline)| Parameter | Type | Description |
|---|---|---|
| timeline | array | An array containing the objects that describe the experiment timeline. See Creating an Experiment: The Timeline. |
None.
Start the jsPsych experiment with the specified timeline.
var timeline = [trial1, trial2, trial3];
jsPsych.run(timeline);jsPsych.timelineVariable(variable)| Parameter | Type | Description |
|---|---|---|
| variable | string | Name of the timeline variable |
Returns a placeholder object that jsPsych uses to evaluate the timeline variable when the trial runs.
Timeline variables are a powerful technique for generating experiments with repetitive procedures but different parameter values. This function fetches the current value of a particular timeline variable. It must be used in conjunction with a timeline that has timeline variables. See the timeline variable section for details.
var trial = {
type: jsPsychImageKeyboardResponse,
stimulus: jsPsych.timelineVariable('image')
}
var procedure = {
timeline: [trial],
timeline_variables: [
{image: 'face1.png'},
{image: 'face2.png'},
{image: 'face3.png'},
{image: 'face4.png'}
]
}jsPsych.version()None.
Returns the version number as a string.
Gets the version of jsPsych.
var version = jsPsych.version();
console.log(version);