replace jsPsych.init with initJsPsych/jsPsych.run in .md files (WIP)

This commit is contained in:
Becky Gilbert 2021-09-16 17:38:51 -07:00
parent 18b536fdf8
commit d6f6df69a9
18 changed files with 107 additions and 132 deletions

View File

@ -8,7 +8,7 @@ jsPsych.extensions['new-extension'] = (function () {
var extension = {}; var extension = {};
extension.initialize = function(params){ extension.initialize = function(params){
// params are passed from the extensions parameter in jsPsych.init // params are passed from the extensions parameter in initJsPsych
} }
extension.on_start = function(params){ extension.on_start = function(params){
@ -32,7 +32,7 @@ jsPsych.extensions['new-extension'] = (function () {
The four events that an extension must support are shown in the sample code. The four events that an extension must support are shown in the sample code.
`extension.initialize` is called with `jsPsych.init()`. This is where setup code for the extension can happen. This event will happen once per experiment, unlike the other events which occur with each trial. The `params` object can include whatever parameters are necessary to configure the extension. The `params` object is passed from the call to `jsPsych.init()` to the `extension.initialize` method. `extension.initialize` must return a `Promise` that resolves when the extension is finished initializing. `extension.initialize` is called with `initJsPsych()`. This is where setup code for the extension can happen. This event will happen once per experiment, unlike the other events which occur with each trial. The `params` object can include whatever parameters are necessary to configure the extension. The `params` object is passed from the call to `initJsPsych()` to the `extension.initialize` method. `extension.initialize` must return a `Promise` that resolves when the extension is finished initializing.
`extension.on_start` is called at the start of the plugin execution, prior to calling `plugin.trial`. This is where trial-specific initialization can happen, such as creating empty containers to hold data or resetting internal state. The `params` object is passed from the declaration of the extension in the trial object. You can use `params` to customize the behavior of the extension for each trial. `extension.on_start` is called at the start of the plugin execution, prior to calling `plugin.trial`. This is where trial-specific initialization can happen, such as creating empty containers to hold data or resetting internal state. The `params` object is passed from the declaration of the extension in the trial object. You can use `params` to customize the behavior of the extension for each trial.

View File

@ -6,10 +6,10 @@ This extension supports eye tracking through the [WebGazer](https://webgazer.cs.
### Initialization Parameters ### Initialization Parameters
Initialization parameters can be set when calling `jsPsych.init()` Initialization parameters can be set when calling `initJsPsych()`
```js ```js
jsPsych.init({ initJsPsych({
extensions: [ extensions: [
{type: 'webgazer', params: {...}} {type: 'webgazer', params: {...}}
] ]

View File

@ -6,11 +6,10 @@ jsPsych offers the ability to call arbitrary functions in response to certain ev
## on_close ## on_close
The `on_close` callback can be declared in the `jsPsych.init` method. The callback triggers when the user leaves the page, but before any content on the page is removed from the browser's memory. This can be used, for example, to save data as the user is leaving the page. The `on_close` callback can be declared in the `initJsPsych` method. The callback triggers when the user leaves the page, but before any content on the page is removed from the browser's memory. This can be used, for example, to save data as the user is leaving the page.
```javascript ```javascript
jsPsych.init({ initJsPsych({
timeline: exp,
on_close: function(){ on_close: function(){
var data = jsPsych.data.get().json(); var data = jsPsych.data.get().json();
save_data_to_server(data); save_data_to_server(data);
@ -22,11 +21,10 @@ jsPsych.init({
## on_data_update ## on_data_update
The `on_data_update` callback can be declared in the `jsPsych.init` method. The callback triggers at the end of a data update cycle. This happens after every trial, after the on_finish (trial) and on_trial_finish events execute, allowing you to modify the data in those callbacks, and then use this callback to store the data. The function will be passed a single argument, which contains the data that was written. The `on_data_update` callback can be declared in the `initJsPsych` method. The callback triggers at the end of a data update cycle. This happens after every trial, after the on_finish (trial) and on_trial_finish events execute, allowing you to modify the data in those callbacks, and then use this callback to store the data. The function will be passed a single argument, which contains the data that was written.
```javascript ```javascript
jsPsych.init({ initJsPsych({
timeline: exp,
on_data_update: function(data) { on_data_update: function(data) {
console.log('Just added new data. The contents of the data are: '+JSON.stringify(data)); console.log('Just added new data. The contents of the data are: '+JSON.stringify(data));
} }
@ -57,11 +55,10 @@ var trial = {
## on_finish (experiment) ## on_finish (experiment)
The `on_finish` callback can be declared in the `jsPsych.init` method. The callback will trigger once all trials in the experiment have been run. The method will be passed a single argument, containing all of the data generated in the experiment. The `on_finish` callback can be declared in the `initJsPsych` method. The callback will trigger once all trials in the experiment have been run. The method will be passed a single argument, containing all of the data generated in the experiment.
```javascript ```javascript
jsPsych.init({ initJsPsych({
timeline: exp,
on_finish: function(data) { on_finish: function(data) {
console.log('The experiment is over! Here is all the data: '+JSON.stringify(data)); console.log('The experiment is over! Here is all the data: '+JSON.stringify(data));
} }
@ -149,11 +146,10 @@ var procedure = {
## on_trial_finish ## on_trial_finish
The `on_trial_finish` callback can be declared in the `jsPsych.init` method. The callback will trigger at the end of every trial in the experiment. If you want a callback to trigger only for the end of certain trials, use the [`on_finish`](#onfinishtrial) callback on the trial object. The callback function will be passed a single argument, containing the data object from the trial. The `on_trial_finish` callback can be declared in the `initJsPsych` method. The callback will trigger at the end of every trial in the experiment. If you want a callback to trigger only for the end of certain trials, use the [`on_finish`](#onfinishtrial) callback on the trial object. The callback function will be passed a single argument, containing the data object from the trial.
```javascript ```javascript
jsPsych.init({ initJsPsych({
timeline: exp,
on_trial_finish: function(data) { on_trial_finish: function(data) {
console.log('A trial just ended.'); console.log('A trial just ended.');
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
@ -165,13 +161,12 @@ jsPsych.init({
## on_trial_start ## on_trial_start
The `on_trial_start` callback can be declared in the `jsPsych.init` method. The callback will trigger at the start of every trial in the experiment. The function receives a single argument: a modifiable copy of the trial object that will be used to run the next trial. Changes can be made to this object to alter the parameters of the upcoming trial. The `on_trial_start` callback can be declared in the `initJsPsych` method. The callback will trigger at the start of every trial in the experiment. The function receives a single argument: a modifiable copy of the trial object that will be used to run the next trial. Changes can be made to this object to alter the parameters of the upcoming trial.
```javascript ```javascript
var current_score = 0; // a variable that is updated throughout the experiment to keep track of the current score. var current_score = 0; // a variable that is updated throughout the experiment to keep track of the current score.
jsPsych.init({ initJsPsych({
timeline: exp,
on_trial_start: function(trial) { on_trial_start: function(trial) {
trial.data.score_at_start_of_trial = current_score; trial.data.score_at_start_of_trial = current_score;
console.log('A trial just started.'); console.log('A trial just started.');

View File

@ -170,8 +170,7 @@ function saveData(name, data){
} }
// call the saveData function after the experiment is over // call the saveData function after the experiment is over
jsPsych.init({ initJsPsych({
// code to define the experiment structure would go here...
on_finish: function(){ saveData(jsPsych.data.get().csv()); } on_finish: function(){ saveData(jsPsych.data.get().csv()); }
}); });
``` ```

View File

@ -1,6 +1,6 @@
# Exclude Participants Based on Browser Features # Exclude Participants Based on Browser Features
Online subjects will use many different kinds of browsers. Depending on the experiment, it may be important to specify a minimum feature set of the browser. jsPsych makes this straightforward. Simply specify certain exclusion criteria in the `jsPsych.init` method call. If a subject's browser doesn't meet the criteria the experiment will not start and the subject will see a message explaining the problem. For size restrictions the subject will see a message that displays the current size of their browser window and the minimum size needed to start the experiment, giving the subject an opportunity to enlarge the browser window to continue. Online subjects will use many different kinds of browsers. Depending on the experiment, it may be important to specify a minimum feature set of the browser. jsPsych makes this straightforward. Simply specify certain exclusion criteria in the `initJsPsych` method call. If a subject's browser doesn't meet the criteria the experiment will not start and the subject will see a message explaining the problem. For size restrictions the subject will see a message that displays the current size of their browser window and the minimum size needed to start the experiment, giving the subject an opportunity to enlarge the browser window to continue.
Current exclusion options: Current exclusion options:
* Minimum browser width & height * Minimum browser width & height
@ -11,8 +11,7 @@ Current exclusion options:
#### Exclude browsers that are not at least 800x600 pixels #### Exclude browsers that are not at least 800x600 pixels
```javascript ```javascript
jsPsych.init({ initJsPsych({
timeline: exp,
exclusions: { exclusions: {
min_width: 800, min_width: 800,
min_height: 600 min_height: 600
@ -23,8 +22,7 @@ jsPsych.init({
#### Exclude browsers that do not have access to the WebAudio API #### Exclude browsers that do not have access to the WebAudio API
```javascript ```javascript
jsPsych.init({ initJsPsych({
timeline: exp,
exclusions: { exclusions: {
audio: true audio: true
} }

View File

@ -1,12 +1,11 @@
# Experiment-wide settings # Experiment-wide settings
There are several options that can be set when calling `jsPsych.init()` to launch the experiment. There are several options that can be set when calling `initJsPsych()` to initialize the jsPsych experiment.
Options are specified in the object passed to `jsPsych.init`. For example, to specify a default inter-trial interval, a minimum valid response time duration, and a maximum width for all of the experiment's page content, the object would contain: Options are specified in the object passed to `initJsPsych`. For example, to specify a default inter-trial interval, a minimum valid response time duration, and a maximum width for all of the experiment's page content, the object would contain:
```js ```js
jsPsych.init({ initJsPsych({
timeline: [...],
default_iti: 250, default_iti: 250,
minimum_valid_rt: 100, minimum_valid_rt: 100,
experiment_width: 800 experiment_width: 800
@ -23,12 +22,12 @@ By default, jsPsych will render the experiment in the `<body>` element of a page
</body> </body>
<script> <script>
initJsPsych({
display_element: 'jspsych-target'
});
// ... // // ... //
jsPsych.init({
timeline: [...],
display_element: 'jspsych-target'
})
</script> </script>
``` ```
@ -51,28 +50,26 @@ Exclusion criteria can be specified based on features of the user's web browser,
## Display a progress bar ## Display a progress bar
An automatic or manually updated progress bar can be displayed at the top of the screen. By default, the text next to the progress bar is "Completion Progress", but this text can be changed with the `message_progress_bar` parameter in `jsPsych.init`. See the [progress bar page](progress-bar.md) for more details. An automatic or manually updated progress bar can be displayed at the top of the screen. By default, the text next to the progress bar is "Completion Progress", but this text can be changed with the `message_progress_bar` parameter in `initJsPsych`. See the [progress bar page](progress-bar.md) for more details.
## Choose the method for playing audio files ## Choose the method for playing audio files
Specifying the `use_webaudio` parameter in `jsPsych.init()` allows you to choose whether to use the WebAudio API or HTML5 audio for playing audio files during your experiment. By default, jsPsych uses the WebAudio API to play audio files. Among other features, the WebAudio API allows for more precise measurement of response times relative to the onset of the audio. Specifying the `use_webaudio` parameter in `initJsPsych()` allows you to choose whether to use the WebAudio API or HTML5 audio for playing audio files during your experiment. By default, jsPsych uses the WebAudio API to play audio files. Among other features, the WebAudio API allows for more precise measurement of response times relative to the onset of the audio.
However, loading files through the WebAudio API causes errors when running an experiment offline (i.e., by double-clicking on the HTML file, rather than hosting it on a web server). This is due to the [cross-origin security policy](https://security.stackexchange.com/a/190321) implemented by web browsers. For this reason, jsPsych switches to a 'safe mode' when it detects that the webpage is running offline, and automatically uses HTML5 audio to prevent errors, even when `use_webaudio` has been explicitly set to `true`. For more information, see the section [Cross-origin requests (CORS) and safe mode](running-experiments.md#cross-origin-requests-cors-and-safe-mode) on the Running Experiments page. However, loading files through the WebAudio API causes errors when running an experiment offline (i.e., by double-clicking on the HTML file, rather than hosting it on a web server). This is due to the [cross-origin security policy](https://security.stackexchange.com/a/190321) implemented by web browsers. For this reason, jsPsych switches to a 'safe mode' when it detects that the webpage is running offline, and automatically uses HTML5 audio to prevent errors, even when `use_webaudio` has been explicitly set to `true`. For more information, see the section [Cross-origin requests (CORS) and safe mode](running-experiments.md#cross-origin-requests-cors-and-safe-mode) on the Running Experiments page.
```js ```js
jsPsych.init({ initJsPsych({
timeline: [...],
use_webaudio: false use_webaudio: false
}); });
``` ```
## Set the default intertrial interval ## Set the default intertrial interval
By default the next trial in a timeline will begin immediately after the conclusion of the previous trial. An experiment-wide delay can be specified using the `default_iti` parameter to `jsPsych.init()`. By default the next trial in a timeline will begin immediately after the conclusion of the previous trial. An experiment-wide delay can be specified using the `default_iti` parameter to `initJsPsych()`.
```js ```js
jsPsych.init({ initJsPsych({
timeline: [...],
default_iti: 500 default_iti: 500
}); });
``` ```
@ -86,8 +83,7 @@ The experiment will, by default, take up 100% of the display element. Usually th
Specifying the `experiment_width` parameter will set a maximum width for the display. The parameter is specified in pixels. Specifying the `experiment_width` parameter will set a maximum width for the display. The parameter is specified in pixels.
```js ```js
jsPsych.init({ initJsPsych({
timeline: [...],
experiment_width: 750 experiment_width: 750
}); });
``` ```
@ -98,8 +94,7 @@ By default, jsPsych will treat any keyboard response time as valid. However, it'
```js ```js
// ignore any keyboard responses that are less than 100 ms // ignore any keyboard responses that are less than 100 ms
jsPsych.init({ initJsPsych({
timeline: [...],
minimum_valid_rt: 100 minimum_valid_rt: 100
}); });
``` ```
@ -108,14 +103,13 @@ jsPsych.init({
JavaScript keyboard events make a distinction between uppercase and lowercase key responses (e.g. 'a' and 'A'). Often the researcher just cares about which physical key was pressed, and not whether the key press would result in an uppercase letter (for instance, if CapsLock is on or if the Shift key is held down). For this reason, jsPsych converts all key choice parameters and key responses as lowercase by default. This makes it easier to specify key choices (e.g. `choices: ['a']`, instead of `choices: ['a','A']`), and it makes it easier to check and score a participant's response. JavaScript keyboard events make a distinction between uppercase and lowercase key responses (e.g. 'a' and 'A'). Often the researcher just cares about which physical key was pressed, and not whether the key press would result in an uppercase letter (for instance, if CapsLock is on or if the Shift key is held down). For this reason, jsPsych converts all key choice parameters and key responses as lowercase by default. This makes it easier to specify key choices (e.g. `choices: ['a']`, instead of `choices: ['a','A']`), and it makes it easier to check and score a participant's response.
There may be situations when you want key choices and responses to be case-sensitive. You can change this by setting the `case_sensitive_responses` parameter to `true` in `jsPsych.init`. There may be situations when you want key choices and responses to be case-sensitive. You can change this by setting the `case_sensitive_responses` parameter to `true` in `initJsPsych`.
```js ```js
// use case-sensitive key choices and responses, // use case-sensitive key choices and responses,
// i.e. uppercase and lower case letters ('a' and 'A') will be treated as different key choices, // i.e. uppercase and lower case letters ('a' and 'A') will be treated as different key choices,
// and will be recorded this way in the data // and will be recorded this way in the data
jsPsych.init({ initJsPsych({
timeline: [...],
case_sensitive_responses: true case_sensitive_responses: true
}); });
``` ```
@ -126,22 +120,20 @@ Note that this setting only applies to key choices and responses that use jsPsyc
By default, jsPsych switches to a 'safe mode' when it detects that the webpage is running offline (via the `file://` protocol) in order to prevent certain errors. Specifically, in safe mode, HTML5 audio is used to play audio files (even when `use_webaudio` has been explicitly set to `true`) and video preloading is disabled (both automatic and manual preloading). For more information, see the [Cross-origin requests (CORS) and safe mode](running-experiments.md#cross-origin-requests-cors-and-safe-mode) section on the Running Experiments page. By default, jsPsych switches to a 'safe mode' when it detects that the webpage is running offline (via the `file://` protocol) in order to prevent certain errors. Specifically, in safe mode, HTML5 audio is used to play audio files (even when `use_webaudio` has been explicitly set to `true`) and video preloading is disabled (both automatic and manual preloading). For more information, see the [Cross-origin requests (CORS) and safe mode](running-experiments.md#cross-origin-requests-cors-and-safe-mode) section on the Running Experiments page.
It's possible to override this safe mode feature by setting the `override_safe_mode` parameter to `true` in `jsPsych.init`. This is something you might do if you've disabled certain security settings in your browser for testing purposes. This parameter has no effect when your experiment is running online (on a server), because it will be using the `http://` or `https://` protocol, which does not trigger safe mode. It's possible to override this safe mode feature by setting the `override_safe_mode` parameter to `true` in `initJsPsych`. This is something you might do if you've disabled certain security settings in your browser for testing purposes. This parameter has no effect when your experiment is running online (on a server), because it will be using the `http://` or `https://` protocol, which does not trigger safe mode.
```js ```js
jsPsych.init({ initJsPsych({
timeline: [...],
override_safe_mode: true override_safe_mode: true
}); });
``` ```
## Add extensions ## Add extensions
Extensions are jsPsych modules that can run throughout the experiment and interface with any plugin to extend the functionality of the plugin. One example of an extension is eye tracking, which allows you to gather gaze data during any trial and add it to that trial's data object. If you want to use extensions in your experiment, you must specify this when you initialize the experiment with `jsPsych.init`. The `extensions` parameter in `jsPsych.init` is an array of objects, where each object specifies the extension that you'd like to use in the experiment. Below is an example of adding the webgazer extension. Extensions are jsPsych modules that can run throughout the experiment and interface with any plugin to extend the functionality of the plugin. One example of an extension is eye tracking, which allows you to gather gaze data during any trial and add it to that trial's data object. If you want to use extensions in your experiment, you must specify this when you initialize the experiment with `initJsPsych`. The `extensions` parameter in `initJsPsych` is an array of objects, where each object specifies the extension that you'd like to use in the experiment. Below is an example of adding the webgazer extension.
```js ```js
jsPsych.init({ initJsPsych({
timeline: [...],
extensions: [ extensions: [
{type: 'webgazer'} {type: 'webgazer'}
] ]

View File

@ -4,7 +4,7 @@ Extensions are jsPsych modules that can interface with any plugin to extend the
## Using an Extension ## Using an Extension
To use an extension in an experiment, you'll load the extension file via a `<script>` tag (just like adding a plugin) and then initialize the extension in the parameters of `jsPsych.init()`. To use an extension in an experiment, you'll load the extension file via a `<script>` tag (just like adding a plugin) and then initialize the extension in the parameters of `initJsPsych()`.
```html ```html
<head> <head>
@ -14,8 +14,7 @@ To use an extension in an experiment, you'll load the extension file via a `<scr
``` ```
```js ```js
jsPsych.init({ initJsPsych({
timeline: [...],
extensions: [ extensions: [
{type: 'some-extension', params: {...} } {type: 'some-extension', params: {...} }
] ]

View File

@ -32,11 +32,10 @@ The [webgazer extension](/extensions/jspsych-ext-webgazer.md) adds functionality
</head> </head>
``` ```
To use the WebGazer extension in an experiment, include it in the list of extensions passed to `jsPsych.init()` To use the WebGazer extension in an experiment, include it in the list of extensions passed to `initJsPsych()`
```js ```js
jsPsych.init({ initJsPsych({
timeline: [...],
extensions: [ extensions: [
{type: 'webgazer'} {type: 'webgazer'}
] ]
@ -184,6 +183,12 @@ If you have tips based on your own experience please consider sharing them on ou
<body></body> <body></body>
<script> <script>
var jsPsych = initJsPsych({
extensions: [
{type: 'webgazer'}
]
});
var preload = { var preload = {
type: 'preload', type: 'preload',
images: ['img/blue.png'] images: ['img/blue.png']
@ -310,25 +315,20 @@ If you have tips based on your own experience please consider sharing them on ou
choices: jsPsych.NO_KEYS choices: jsPsych.NO_KEYS
}; };
jsPsych.init({ jsPsych.run([
timeline: [ preload,
preload, camera_instructions,
camera_instructions, init_camera,
init_camera, calibration_instructions,
calibration_instructions, calibration,
calibration, validation_instructions,
validation_instructions, validation,
validation, recalibrate,
recalibrate, calibration_done,
calibration_done, begin,
begin, trial,
trial, show_data
show_data ]);
],
extensions: [
{type: 'webgazer'}
]
});
</script> </script>
</html> </html>

View File

@ -3,6 +3,8 @@
You can run your experiment in fullscreen mode by using the jspsych-fullscreen plugin. You can run your experiment in fullscreen mode by using the jspsych-fullscreen plugin.
```javascript ```javascript
var jsPsych = initJsPsych();
var timeline = []; var timeline = [];
timeline.push({ timeline.push({
@ -26,9 +28,7 @@ timeline.push({
stimulus: 'This trial will NOT be in fullscreen mode.' stimulus: 'This trial will NOT be in fullscreen mode.'
}); });
jsPsych.init({ jsPsych.run(timeline);
timeline: timeline
});
``` ```
For security reasons, web browsers require that users initiate an action to launch fullscreen mode. The fullscreen plugin displays a button that the user must click to change the display to fullscreen. For security reasons, web browsers require that users initiate an action to launch fullscreen mode. The fullscreen plugin displays a button that the user must click to change the display to fullscreen.

View File

@ -77,9 +77,9 @@ Note the use of the data parameter to add a property `stimulus_type` with the va
### The post_trial_gap (ITI) parameter ### The post_trial_gap (ITI) parameter
The default inter-trial interval (ITI) in jsPsych is 0 ms. This can be adjusted at the experiment-wide level by changing the `default_iti` parameter in `jsPsych.init()`. The default inter-trial interval (ITI) in jsPsych is 0 ms. This can be adjusted at the experiment-wide level by changing the `default_iti` parameter in `initJsPsych()`.
The ITI can also be controlled at the trial level through the `post_trial_gap` parameter. Setting this parameter to a positive integer *x* will cause a blank screen to display after the trial for *x* milliseconds. Setting this parameter for a trial will override the `default_iti` value set in `jsPsych.init`. The ITI can also be controlled at the trial level through the `post_trial_gap` parameter. Setting this parameter to a positive integer *x* will cause a blank screen to display after the trial for *x* milliseconds. Setting this parameter for a trial will override the `default_iti` value set in `initJsPsych`.
```javascript ```javascript
var trial = { var trial = {

View File

@ -4,11 +4,10 @@ jsPsych can show a progress bar at the top of the experiment page indicating the
![Progressbar Screenshot](/img/progress_bar.png) ![Progressbar Screenshot](/img/progress_bar.png)
To show the progress bar, set the `show_progress_bar` option in `jsPsych.init` to `true`: To show the progress bar, set the `show_progress_bar` option in `initJsPsych` to `true`:
```javascript ```javascript
jsPsych.init({ var jsPsych = initJsPsych({
timeline: exp,
show_progress_bar: true show_progress_bar: true
}); });
``` ```
@ -35,19 +34,23 @@ You can also get the current value of the progress bar with `jsPsych.getProgress
var proportion_complete = jsPsych.getProgressBarCompleted(); var proportion_complete = jsPsych.getProgressBarCompleted();
``` ```
If you are going to use manual progress bar control, you may want to disable the automatic progress bar updates by setting the `auto_update_progress_bar` property in `jsPsych.init()` to `false`. If you are going to use manual progress bar control, you may want to disable the automatic progress bar updates by setting the `auto_update_progress_bar` property in `initJsPsych()` to `false`.
```js ```js
jsPsych.init({ var jsPsych = initJsPsych({
timeline: exp,
show_progress_bar: true, show_progress_bar: true,
auto_update_progress_bar: false auto_update_progress_bar: false
}); });
``` ```
Here's a complete example showing how to use these functions and `jsPsych.init()` settings to manually update the progress bar: Here's a complete example showing how to use these functions and `initJsPsych()` settings to manually update the progress bar:
```js ```js
var jsPsych = initJsPsych({
show_progress_bar: true,
auto_update_progress_bar: false
});
var n_trials = 5; var n_trials = 5;
var start = { var start = {
@ -80,21 +83,16 @@ var done = {
stimulus: 'Done!' stimulus: 'Done!'
}; };
jsPsych.init({ jsPsych.run([start, trials, done]);
timeline: [start, trials, done],
show_progress_bar: true,
auto_update_progress_bar: false
});
``` ```
## Custom Text ## Custom Text
By default, jsPsych adds the text "Completion Progress" to the left of the progress bar. You can specify custom text using the `message_progress_bar` parameter in `jsPsych.init`. By default, jsPsych adds the text "Completion Progress" to the left of the progress bar. You can specify custom text using the `message_progress_bar` parameter in `initJsPsych`.
```js ```js
// support for different spoken languages // support for different spoken languages
jsPsych.init({ var jsPsych = initJsPsych({
timeline: [...],
show_progress_bar: true, show_progress_bar: true,
message_progress_bar: 'Porcentaje completo' message_progress_bar: 'Porcentaje completo'
}); });
@ -102,8 +100,7 @@ jsPsych.init({
```js ```js
// no message // no message
jsPsych.init({ var jsPsych = initJsPsych({
timeline: [...],
show_progress_bar: true, show_progress_bar: true,
message_progress_bar: '' message_progress_bar: ''
}); });

View File

@ -14,6 +14,8 @@ We can capture these variables with jsPsych, and add them to jsPsych's data. Thi
```html ```html
<script> <script>
var jsPsych = initJsPsych();
// capture info from Prolific // capture info from Prolific
var subject_id = jsPsych.data.getURLVariable('PROLIFIC_PID'); var subject_id = jsPsych.data.getURLVariable('PROLIFIC_PID');
var study_id = jsPsych.data.getURLVariable('STUDY_ID'); var study_id = jsPsych.data.getURLVariable('STUDY_ID');
@ -28,9 +30,7 @@ We can capture these variables with jsPsych, and add them to jsPsych's data. Thi
// create the rest of the experiment // create the rest of the experiment
var timeline = [...] var timeline = [...]
jsPsych.init({ jsPsych.run(timeline)
timeline: timeline
})
</script> </script>
``` ```
@ -67,8 +67,7 @@ A second option is to automatically redirect the participant to the completion U
Here's an example using the `on_finish` event for the entire experiment. Here's an example using the `on_finish` event for the entire experiment.
```js ```js
jsPsych.init({ var jsPsych = initJsPsych({
timeline: [...],
on_finish: function(){ on_finish: function(){
window.location = "https://app.prolific.co/submissions/complete?cc=XXXXXXX" window.location = "https://app.prolific.co/submissions/complete?cc=XXXXXXX"
} }

View File

@ -12,10 +12,10 @@ Each time the user leaves the experiment window, returns to the experiment windo
} }
``` ```
You can specify a custom function, in the jsPsych.init() method, that is called whenever one of these events occurs You can specify a custom function, in the initJsPsych() method, that is called whenever one of these events occurs
```javascript ```javascript
jsPsych.init({ initJsPsych({
on_interaction_data_update: function(data) { on_interaction_data_update: function(data) {
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
} }

View File

@ -27,12 +27,12 @@ Web browsers have a security policy called [cross-origin resource sharing (CORS)
To prevent these errors, jsPsych uses a 'safe mode' when it detects that the HTML page is running via the `file://` protocol, and if so, automatically disables the features that don't work in that context. Specifically, when a jsPsych experiment runs offline: To prevent these errors, jsPsych uses a 'safe mode' when it detects that the HTML page is running via the `file://` protocol, and if so, automatically disables the features that don't work in that context. Specifically, when a jsPsych experiment runs offline:
* **Web Audio is disabled** (even if `use_webaudio` is set to `true` in `jsPsych.init`). The WebAudio API option is used by default because it allows more precise measurement of response times relative to the onset of the audio. But because WebAudio doesn't work offline, audio will be played using HTML5 audio instead. This is equivalent to setting `use_webaudio` to `false` in `jsPsych.init`. * **Web Audio is disabled** (even if `use_webaudio` is set to `true` in `initJsPsych`). The WebAudio API option is used by default because it allows more precise measurement of response times relative to the onset of the audio. But because WebAudio doesn't work offline, audio will be played using HTML5 audio instead. This is equivalent to setting `use_webaudio` to `false` in `initJsPsych`.
* **Video preloading is disabled** (both automatic and manual preloading via the `preload` plugin). Videos will still play when you run your experiment offline, but they will load _during_ the experiment, which might cause noticeable delays before video playback starts. * **Video preloading is disabled** (both automatic and manual preloading via the `preload` plugin). Videos will still play when you run your experiment offline, but they will load _during_ the experiment, which might cause noticeable delays before video playback starts.
This safe mode feature is controlled by the `override_safe_mode` parameter in [`jsPsych.init`](/reference/jspsych.md#jspsychinit), which defaults to `false`. If you leave this setting as the default, then you won't need to worry about CORS errors while running your experiment offline, or remembering to change your `jsPsych.init` settings when you move the experiment online. This safe mode feature is controlled by the `override_safe_mode` parameter in [`initJsPsych`](/reference/jspsych.md#jspsychinit), which defaults to `false`. If you leave this setting as the default, then you won't need to worry about CORS errors while running your experiment offline, or remembering to change your `initJsPsych` settings when you move the experiment online.
It's possible to override jsPsych's safe mode by setting `override_safe_mode` to `true` in `jsPsych.init`. One reason you might do this is if you've disabled web security features in your browser (see [here](https://alfilatov.com/posts/run-chrome-without-cors/) and [here](https://stackoverflow.com/questions/4819060/allow-google-chrome-to-use-xmlhttprequest-to-load-a-url-from-a-local-file) for instructions in Chrome), which is safe to do if you know what you're doing. If your experiment does not use Web Audio or preloaded videos, then jsPsych's safe mode feature will not have any effect. It's possible to override jsPsych's safe mode by setting `override_safe_mode` to `true` in `initJsPsych`. One reason you might do this is if you've disabled web security features in your browser (see [here](https://alfilatov.com/posts/run-chrome-without-cors/) and [here](https://stackoverflow.com/questions/4819060/allow-google-chrome-to-use-xmlhttprequest-to-load-a-url-from-a-local-file) for instructions in Chrome), which is safe to do if you know what you're doing. If your experiment does not use Web Audio or preloaded videos, then jsPsych's safe mode feature will not have any effect.
The `override_safe_mode` parameter also has no effect when your experiment is running online a web server, because the page will be loaded via the `http://` or `https://` protocol. The `override_safe_mode` parameter also has no effect when your experiment is running online a web server, because the page will be loaded via the `http://` or `https://` protocol.

View File

@ -4,7 +4,7 @@ To create an experiment using jsPsych, you need to specify a timeline that descr
## A single trial ## A single trial
To create a trial, you need to create an object that describes the trial. The most important feature of this object is the `type` parameter. This tells jsPsych which plugin file to use to run the trial. For example, if you want to use the text plugin to display a short message, the trial object would look like this: To create a trial, you need to create an object that describes the trial. The most important feature of this object is the `type` parameter. This tells jsPsych which plugin to use to run the trial. For example, if you want to use the text plugin to display a short message, the trial object would look like this:
```javascript ```javascript
var trial = { var trial = {
@ -20,9 +20,7 @@ To create a timeline with the single trial and run the experiment, just embed th
```javascript ```javascript
var timeline = [trial]; var timeline = [trial];
jsPsych.init({ jsPsych.run(timeline);
timeline: timeline
});
``` ```
To actually create and run this simple example, complete the [hello world tutorial](../tutorials/hello-world.md). To actually create and run this simple example, complete the [hello world tutorial](../tutorials/hello-world.md).
@ -366,6 +364,8 @@ var loop_node = {
A timeline can be skipped based on the evaluation of a function using the `conditional_function` option. If the conditional function evaluates to `true`, the timeline will execute normally. If the conditional function evaluates to `false`, then the timeline will be skipped. The conditional function is evaluated whenever the timeline is about to run the first trial. A timeline can be skipped based on the evaluation of a function using the `conditional_function` option. If the conditional function evaluates to `true`, the timeline will execute normally. If the conditional function evaluates to `false`, then the timeline will be skipped. The conditional function is evaluated whenever the timeline is about to run the first trial.
```javascript ```javascript
var jsPsych = initJsPsych();
var pre_if_trial = { var pre_if_trial = {
type: 'html-keyboard-response', type: 'html-keyboard-response',
stimulus: 'The next trial is in a conditional statement. Press S to skip it, or V to view it.' stimulus: 'The next trial is in a conditional statement. Press S to skip it, or V to view it.'
@ -395,10 +395,7 @@ var after_if_trial = {
stimulus: 'This is the trial after the conditional.' stimulus: 'This is the trial after the conditional.'
} }
jsPsych.init({ jsPsych.run([pre_if_trial, if_node, after_if_trial]);
timeline: [pre_if_trial, if_node, after_if_trial],
on_finish: function(){jsPsych.data.displayData(); }
});
``` ```
## Timeline start and finish functions ## Timeline start and finish functions

View File

@ -6,13 +6,13 @@ The preload trial will end as soon as all files have loaded successfully. The tr
## Parameters ## Parameters
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. While there are no specific parameters that are required, the plugin expects to be given a set of files to load through one or more of the following parameters: `auto_preload` or `trials` (for automatic loading), and/or `images`, `audio`, `video` (for manual loading). To automatically load files based on a timeline of trials, either set the `auto_preload` parameter is `true` (to load files based on the main timeline passed to `jsPsych.init`) or use the `trials` parameter to load files based on a specific subset of trials. To manually load a set of files, use the `images`, `audio`, and `video` parameters. You can combine automatic and manual loading methods in a single preload trial. In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. While there are no specific parameters that are required, the plugin expects to be given a set of files to load through one or more of the following parameters: `auto_preload` or `trials` (for automatic loading), and/or `images`, `audio`, `video` (for manual loading). To automatically load files based on a timeline of trials, either set the `auto_preload` parameter is `true` (to load files based on the main timeline passed to `jsPsych.run`) or use the `trials` parameter to load files based on a specific subset of trials. To manually load a set of files, use the `images`, `audio`, and `video` parameters. You can combine automatic and manual loading methods in a single preload trial.
All other parameters can be left unspecified if the default value is acceptable. All other parameters can be left unspecified if the default value is acceptable.
| Parameter | Type | Default Value | Description | | Parameter | Type | Default Value | Description |
| --------------------- | -------------- | -------------------------------- | ---------------------------------------- | | --------------------- | -------------- | -------------------------------- | ---------------------------------------- |
| auto_preload | boolean | false | If `true`, the plugin will preload any files that can be automatically preloaded based on the main experiment timeline that is passed to `jsPsych.init`. If `false`, any file(s) to be preloaded should be specified by passing a timeline array to the `trials` parameter and/or an array of file paths to the `images`, `audio`, and/or `video` parameters. Setting this parameter to `false` is useful when you plan to preload your files in smaller batches throughout the experiment. | | auto_preload | boolean | false | If `true`, the plugin will preload any files that can be automatically preloaded based on the main experiment timeline that is passed to `jsPsych.run`. If `false`, any file(s) to be preloaded should be specified by passing a timeline array to the `trials` parameter and/or an array of file paths to the `images`, `audio`, and/or `video` parameters. Setting this parameter to `false` is useful when you plan to preload your files in smaller batches throughout the experiment. |
| trials | timeline array | [] | An array containing one or more jsPsych trial or timeline objects. This parameter is useful when you want to automatically preload stimuli files from a specific subset of the experiment. See [Creating an Experiment: The Timeline](/overview/timeline) for information on constructing timelines. | | trials | timeline array | [] | An array containing one or more jsPsych trial or timeline objects. This parameter is useful when you want to automatically preload stimuli files from a specific subset of the experiment. See [Creating an Experiment: The Timeline](/overview/timeline) for information on constructing timelines. |
| images | array | [] | Array containing file paths for one or more image files to preload. This option is typically used for image files that can't be automatically preloaded from the timeline. | | images | array | [] | Array containing file paths for one or more image files to preload. This option is typically used for image files that can't be automatically preloaded from the timeline. |
| audio | array | [] | Array containing file paths for one or more audio files to preload. This option is typically used for audio files that can't be automatically preloaded from the timeline. | | audio | array | [] | Array containing file paths for one or more audio files to preload. This option is typically used for audio files that can't be automatically preloaded from the timeline. |
@ -105,6 +105,8 @@ In addition to the [default data collected by all plugins](/overview/plugins/#da
???+ example "Loading files in batches" ???+ example "Loading files in batches"
=== "Code" === "Code"
```javascript ```javascript
var jsPsych = initJsPsych();
var trial_1 = { var trial_1 = {
type: 'image-button-response', type: 'image-button-response',
stimulus: 'img/happy_face_1.jpg', stimulus: 'img/happy_face_1.jpg',
@ -159,9 +161,7 @@ In addition to the [default data collected by all plugins](/overview/plugins/#da
trials: [block_2] trials: [block_2]
} }
jsPsych.init({ jsPsych.run([preload_block_1, block_1, preload_block_2, block_2])
timeline: [preload_block_1, block_1, preload_block_2, block_2]
})
``` ```
You can put trials using the `preload` plugin throughout your experiment to distribute when files are loaded. In the example above, there are two blocks of trials and the images for each are preloaded just before the corresponding block. You can put trials using the `preload` plugin throughout your experiment to distribute when files are loaded. In the example above, there are two blocks of trials and the images for each are preloaded just before the corresponding block.

View File

@ -59,8 +59,7 @@ Outputs all of the data collected in the experiment to the screen in either JSON
#### Using the on_finish callback function to show data at the end of the experiment #### Using the on_finish callback function to show data at the end of the experiment
```javascript ```javascript
jsPsych.init({ var jsPsych = initJsPsych({
experiment_structure: exp,
on_finish: function() { on_finish: function() {
jsPsych.data.displayData('csv'); jsPsych.data.displayData('csv');
} }

View File

@ -109,7 +109,7 @@ Returns true if keycodes or strings refer to the same key, regardless of type. R
Compares two keys to see if they are the same, ignoring differences in representational type, and using the appropriate case sensitivity based on the experiment's settings. Compares two keys to see if they are the same, ignoring differences in representational type, and using the appropriate case sensitivity based on the experiment's settings.
If `case_sensitive_responses` is set to `false` in `jsPsych.init` (the default), then the string key comparison will not be case-sensitive, e.g., "a" and "A" will match, and this function will return `true`. If `case_sensitive_responses` is set to `true` in `jsPsych.init`, then the string key comparison will not be case-sensitive, e.g., "a" and "A" will not match, and this function will return `false`. If `case_sensitive_responses` is set to `false` in `initJsPsych` (the default), then the string key comparison will not be case-sensitive, e.g., "a" and "A" will match, and this function will return `true`. If `case_sensitive_responses` is set to `true` in `initJsPsych`, then the string key comparison will not be case-sensitive, e.g., "a" and "A" will not match, and this function will return `false`.
We recommend using this function to compare keys in all plugin and experiment code, rather than using something like `if (response == 'j')...`. This is because the response key returned by the `jsPsych.pluginAPI.getKeyboardResponse` function will be converted to lowercase when `case_sensitive_responses` is `false`, and it will match the exact key press representation when `case_sensitive_responses` is `true`. Using this `compareKeys` function will ensure that your key comparisons work appropriately based on the experiment's `case_sensitive_responses` setting, and that you do not need to remember to check key responses against different case versions of the comparison key (e.g. `if (response == 'ArrowLeft' || response == 'arrowleft')...`). We recommend using this function to compare keys in all plugin and experiment code, rather than using something like `if (response == 'j')...`. This is because the response key returned by the `jsPsych.pluginAPI.getKeyboardResponse` function will be converted to lowercase when `case_sensitive_responses` is `false`, and it will match the exact key press representation when `case_sensitive_responses` is `true`. Using this `compareKeys` function will ensure that your key comparisons work appropriately based on the experiment's `case_sensitive_responses` setting, and that you do not need to remember to check key responses against different case versions of the comparison key (e.g. `if (response == 'ArrowLeft' || response == 'arrowleft')...`).
@ -119,10 +119,10 @@ We recommend using this function to compare keys in all plugin and experiment co
```javascript ```javascript
jsPsych.pluginAPI.compareKeys('a', 'A'); jsPsych.pluginAPI.compareKeys('a', 'A');
// returns true when case_sensitive_responses is false in jsPsych.init // returns true when case_sensitive_responses is false in initJsPsych
jsPsych.pluginAPI.compareKeys('a', 'A'); jsPsych.pluginAPI.compareKeys('a', 'A');
// returns false when case_sensitive_responses is true in jsPsych.init // returns false when case_sensitive_responses is true in initJsPsych
// also works with numeric key codes (but note that numeric keyCode values are now deprecated) // also works with numeric key codes (but note that numeric keyCode values are now deprecated)
jsPsych.pluginAPI.compareKeys('a', 65); jsPsych.pluginAPI.compareKeys('a', 65);
@ -297,11 +297,11 @@ Return an object that uniquely identifies the keyboard listener. This object can
Gets a keyboard response from the subject, recording the response time from when the function is first called until a valid response is generated. Gets a keyboard response from the subject, recording the response time from when the function is first called until a valid response is generated.
The keyboard event listener will be bound to the `display_element` declared in `jsPsych.init()` (or the `<body>` element if no `display_element` is specified). This allows jsPsych experiments to be embedded in websites with other content without disrupting the functionality of other UI elements. The keyboard event listener will be bound to the `display_element` declared in `initJsPsych()` (or the `<body>` element if no `display_element` is specified). This allows jsPsych experiments to be embedded in websites with other content without disrupting the functionality of other UI elements.
A valid response triggers the `callback_function` specified in the parameters. A single argument is passed to the callback function. The argument contains an object with the properties `key` and `rt`. `key` contains the string representation of the response key, and `rt` contains the response time. A valid response triggers the `callback_function` specified in the parameters. A single argument is passed to the callback function. The argument contains an object with the properties `key` and `rt`. `key` contains the string representation of the response key, and `rt` contains the response time.
This function uses the `.key` value of the keyboard event, which is _case sensitive_. When `case_sensitive_responses` is `false` in `jsPsych.init` (the default), this function will convert both the `valid_responses` strings and the response key to lowercase before comparing them, and it will pass the lowercase version of the response key to the `callback_function`. For example, if `valid_responses` is `['a']`, then both 'A' and 'a' will be considered valid key presses, and 'a' will be returned as the response key. When `case_sensitive_responses` is `true` in `jsPsych.init`, this function will not convert the case when comparing the `valid_responses` and response key, and it will not convert the case of the response key that is passed to the `callback_function`. For example, if `valid_responses` is `['a']`, then 'a' will be the only valid key press, and 'A' (i.e. 'a' with CapsLock on or Shift held down) will not be accepted. Also, if `valid_responses` includes multiple letter case options (e.g. `jsPsych.ALL_KEYS`), then you may need to check the response key against both letter cases when scoring etc., e.g. `if (response == 'ArrowLeft' || response =='arrowleft') ...`. This function uses the `.key` value of the keyboard event, which is _case sensitive_. When `case_sensitive_responses` is `false` in `initJsPsych` (the default), this function will convert both the `valid_responses` strings and the response key to lowercase before comparing them, and it will pass the lowercase version of the response key to the `callback_function`. For example, if `valid_responses` is `['a']`, then both 'A' and 'a' will be considered valid key presses, and 'a' will be returned as the response key. When `case_sensitive_responses` is `true` in `initJsPsych`, this function will not convert the case when comparing the `valid_responses` and response key, and it will not convert the case of the response key that is passed to the `callback_function`. For example, if `valid_responses` is `['a']`, then 'a' will be the only valid key press, and 'A' (i.e. 'a' with CapsLock on or Shift held down) will not be accepted. Also, if `valid_responses` includes multiple letter case options (e.g. `jsPsych.ALL_KEYS`), then you may need to check the response key against both letter cases when scoring etc., e.g. `if (response == 'ArrowLeft' || response =='arrowleft') ...`.
### Examples ### Examples