Merge branch 'master' into pr/pjkohler/1442

This commit is contained in:
Josh de Leeuw 2021-02-18 16:58:00 -05:00
commit 3152d16468
254 changed files with 104516 additions and 5944 deletions

View File

@ -3,11 +3,7 @@
name: Jest Test
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
on: [ push, pull_request ]
jobs:
build:

View File

@ -1,19 +1,61 @@
The following people have contributed to the development of jsPsych by writing code, documentation, and/or suggesting improvements (in alphabetical order):
* alisdt - https://github.com/alisdt
* Antonia - https://github.com/Ahoidal
* aucuparia - https://github.com/aucuparia
* Xiaolu Bai - https://github.com/lbai001
* bjoluc - https://github.com/bjoluc
* Christian Brickhouse - https://github.com/chrisbrickhouse
* Teon L Brooks - https://github.com/teonbrooks
* Eamon Caddigan - https://github.com/eamoncaddigan
* Jason Carpenter
* Steve Chao - https://github.com/stchao
* Krisitn Diep - https://github.com/kristiyip
* Zhanwen "Phil" Chen - https://github.com/zhanwenchen
* cthorey - https://github.com/cthorey
* Guy Davidson - https://github.com/guydav
* Kristin Diep - https://github.com/kristiyip
* Ari Dyckovsky - https://github.com/aridyckovsky
* Etienne Gaudrain - https://github.com/egaudrain
* Jon Gauthier - https://github.com/hans
* Robert Gibboni - https://github.com/r-b-g-b
* Becky Gilbert - https://github.com/becky-gilbert
* Mark Gorenstein - https://github.com/mgorenstein
* Rui Han - https://github.com/hrcn
* Andy Heusser - https://github.com/andrewheusser
* Angus Hughes - https://github.com/awhug
* Gustavo Juantorena - https://github.com/GEJ1
* Chris Jungerius - https://github.com/cjungerius
* George Kachergis - https://github.com/kachergis
* Yul Kang - https://github.com/yulkang
* Spencer King - https://github.com/spencerking
* Jana Klaus - https://github.com/janakl4us
* Arnold Kochari - https://github.com/akochari
* Peter Jes Kohler - https://github.com/pjkohler
* kupiqu - https://github.com/kupiqu
* Daiichiro Kuroki - https://github.com/kurokida
* Jonas Lambers
* madebyafox - https://github.com/madebyafox
* Shane Martin - https://github.com/shamrt
* Vijay Marupudi - https://github.com/vijaymarupudi
* Adrian Oesch - https://github.com/adrianoesch
* Benjamin Ooghe-Tabanou - https://github.com/boogheta
* Dillon Plunkett - https://github.com/dillonplunkett
* Junyan Qi - https://github.com/GavinQ1
* Sivananda Rajananda - https://github.com/vrsivananda
* Dan Rivas - https://github.com/rivasd
* Werner Sævland - https://github.com/wernersa
* Marian Sauter - https://github.com/mariansauter
* Ellen Shapiro - https://github.com/designatednerd
* Jan Simson - https://github.com/jansim
* Hannah Small - https://github.com/hesmall
* sprengholz - https://github.com/sprengholz
* Dominik Strohmeier - https://github.com/onkeltom
* Nabeel Sulieman - https://github.com/nabsul
* Hitoshi Tominaga - https://github.com/tbrotherm
* Tim Vergenz - https://github.com/vergenzt
* Matteo Visconti di Oleggio Castello - https://github.com/mvdoc
* Ilya Vorontsov - https://github.com/VorontsovIE
* Wolfgang Walther - https://github.com/wolfgangwalther
* Erik Weitnauer - https://github.com/eweitnauer
* Rob Wilkinson - https://github.com/RobAWilkinson
* Andy Woods - https://github.com/andytwoods
* Reto Wyss - https://github.com/retowyss

View File

@ -76,9 +76,17 @@
border-color: #ccc;
}
.jspsych-btn:hover {
/* only apply the hover style on devices with a mouse/pointer that can hover - issue #977 */
@media (hover: hover) {
.jspsych-btn:hover {
background-color: #ddd;
border-color: #aaa;
}
}
.jspsych-btn:active {
background-color: #ddd;
border-color: #aaa;
border-color:#000000;
}
.jspsych-btn:disabled {
@ -88,6 +96,79 @@
cursor: not-allowed;
}
/* custom style for input[type="range] (slider) to improve alignment between positions and labels */
.jspsych-slider {
appearance: none;
-webkit-appearance: none;
-moz-appearance: none;
width: 100%;
background: transparent;
}
.jspsych-slider:focus {
outline: none;
}
/* track */
.jspsych-slider::-webkit-slider-runnable-track {
appearance: none;
-webkit-appearance: none;
width: 100%;
height: 8px;
cursor: pointer;
background: #eee;
box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
border-radius: 2px;
border: 1px solid #aaa;
}
.jspsych-slider::-moz-range-track {
appearance: none;
width: 100%;
height: 8px;
cursor: pointer;
background: #eee;
box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
border-radius: 2px;
border: 1px solid #aaa;
}
.jspsych-slider::-ms-track {
appearance: none;
width: 99%;
height: 14px;
cursor: pointer;
background: #eee;
box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
border-radius: 2px;
border: 1px solid #aaa;
}
/* thumb */
.jspsych-slider::-webkit-slider-thumb {
border: 1px solid #666;
height: 24px;
width: 15px;
border-radius: 5px;
background: #ffffff;
cursor: pointer;
-webkit-appearance: none;
margin-top: -9px;
}
.jspsych-slider::-moz-range-thumb {
border: 1px solid #666;
height: 24px;
width: 15px;
border-radius: 5px;
background: #ffffff;
cursor: pointer;
}
.jspsych-slider::-ms-thumb {
border: 1px solid #666;
height: 20px;
width: 15px;
border-radius: 5px;
background: #ffffff;
cursor: pointer;
margin-top: -2px;
}
/* jsPsych progress bar */
#jspsych-progressbar-container {

View File

@ -6,21 +6,21 @@ Contributions to jsPsych are welcome! All of the code is managed through the Git
#### Discuss the proposed change
If you have a specific modification in mind, open a [new issue via GitHub](https://github.com/jspsych/jsPsych/issues/new). Describe the proposed change and what problem it solves. If you are interested in adding a new plugin to the library, it helps if you post an example of the plugin in use and describe the different use cases of the plugin.
If you have a specific modification in mind -- for instance, a new feature or bug fix -- please open a [new issue via GitHub](https://github.com/jspsych/jsPsych/issues/new). Describe the proposed change and what functionality it adds to the library and/or what problem it solves. If you are interested in adding a new plugin to the library, it helps if you post an example of the plugin in use and describe the different use cases of the plugin (for more guidance, see the "Writing new plugins" section below).
If the modification you are interested in working on is not quite at the point where you have a specific modification to the code base in mind, then it might be helpful to discuss the issue first on the [jsPsych Google group](https://groups.google.com/forum/#!forum/jspsych).
If you are thinking about proposing a change but not at the point where you have a specific modification to the code base in mind, then it might be helpful to discuss the issue first on [GitHub Discussions](https://github.com/jspsych/jsPsych/discussions). Discussion posts can be useful for sharing code and getting feedback before requesting a change to the library.
#### Fork the library and modify the code
To make changes to the code, you should fork the jsPsych library via GitHub. Changes should be targeted at the `master` branch.
To make changes to the code, you should fork the jsPsych library via GitHub and make modifications on your fork. You may find it useful to make modifications on branches, so that you can keep your proposed changes separate from any other unrelated changes you might want to make on your fork.
#### Submit a pull request
Once your modification is complete, submit a pull request to merge your changes into the main repository. Pull requests will be reviewed by the project owner.
Once your modification is complete, submit a pull request to merge your changes into the `master` branch of the main repository. Pull requests will be reviewed by the project team.
## Writing new plugins
New plugins are welcome additions to the library. Plugins can be distributed independently of the main library or added to the GitHub repository via a pull request and the process described above. If you want to add your plugin to the main library then there are a few guidelines to follow.
New plugins are welcome additions to the library. Plugins can be distributed independently of the main library or added to the GitHub repository via a pull request, following the process described above. If you want to add your plugin to the main library then there are a few guidelines to follow.
#### Make the plugin as general as possible
@ -28,7 +28,7 @@ Plugins are most useful when they are flexible. Avoid fixing the value of parame
#### Use the jsPsych.pluginAPI module when appropriate
The pluginAPI module contains functions relevant to plugin development. Avoid duplicating the functions defined within the library in your plugin. If you have a suggestion for improving pluginAPI methods, then go ahead and submit a pull request to modify it directly.
The [pluginAPI module](../core_library/jspsych-pluginAPI.md) contains functions relevant to plugin development. Avoid duplicating the functions defined within the library in your plugin, and instead use the pluginAPI whenever possible. If you have a suggestion for improving pluginAPI methods, then go ahead and submit a pull request to modify it directly.
#### Document your plugin
@ -36,7 +36,7 @@ When submitting a pull request to add your plugin, make sure to include a docume
#### Include an example file
Write a short example file to include in the `examples` directory. This should demonstrate the basic use cases of the plugin as clearly as possible.
Write a short example HTML file to include in the `examples` directory. This should demonstrate the basic use cases of the plugin as clearly as possible.
#### Include a testing file

View File

@ -1,7 +1,7 @@
# Support
For questions about jsPsych the preferred method of support is the [jsPsych Google group](https://groups.google.com/forum/#!forum/jspsych). Questions are most likely to be answered when they include a reproducible example of the problem. If you can make your code available online and link to the experiment, that will make the question easier to answer.
For questions about jsPsych the preferred method of support is via [GitHub Discussions](https://github.com/jspsych/jsPsych/discussions). Questions are most likely to be answered when they include a reproducible example of the problem. If you can make your code available online and link to the experiment, that will make the question easier to answer.
If you have identified a problem with jsPsych, such as a bug in the code or an error in the documentation, please [open a new issue](https://github.com/jodeleeuw/jsPsych/issues) on the GitHub site.
If you have identified a problem with jsPsych, such as a bug in the code or an error in the documentation, please [open a new issue](https://github.com/jspsych/jsPsych/issues/new) on the GitHub site. And if you have a suggestion for fixing the problem, feel free to propose a modification by following the steps in the [Contribuitng to jsPsych](contributing.md) page.
Inquiries for paid consultation to develop experiments using jsPsych or to create new custom jsPsych features can be sent to [josh.deleeuw@gmail.com](mailto:josh.deleeuw@gmail.com).

View File

@ -3,15 +3,14 @@
---
## jsPsych.addNodeToEndOfTimeline
```
jsPsych.addNodeToEndOfTimeline(node_parameters, callback)
jsPsych.addNodeToEndOfTimeline(node_parameters)
```
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
node_parameters | object | An object defining a timeline. It must have, at a minimum, a `timeline` parameter with a valid timeline array as the value for that parameter.
callback | function | An optional callback function. If adding the node to the timeline requires any preloading of media assets, this callback will be triggered after preloading is compelte.
| Parameter | Type | Description |
| --------------- | -------- | ---------------------------------------- |
| node_parameters | object | An object defining a timeline. It must have, at a minimum, a `timeline` parameter with a valid timeline array as the value for that parameter. |
### Return value
@ -56,6 +55,39 @@ var first = {
}
```
---
## jsPsych.allTimelineVariables
```
jsPsych.allTimelineVariables()
```
### Parameters
None.
### Return value
Returns an object with all available timeline variables at this moment in the experiment, represented as `key: value` pairs.
### Description
This function can be used to get all the timeline variables at a particular moment in the experiment. Can be useful for annotating
data, such as in the example below.
### Example
```javascript
var trial = {
type: 'html-keyboard-response',
stimulus: 'Just a demo',
on_finish: function(data){
// merge all timeline variables available at this trial into the data for this trial
Object.assign(data, jsPsych.allTimelineVariables())
}
}
```
---
## jsPsych.currentTimelineNodeID
@ -151,7 +183,7 @@ Ends the current timeline. If timelines are nested, then only the timeline that
### Example
#### Loop indefinitely until a particular key is pressed
#### End timeline if a particular key is pressed
```javascript
@ -170,10 +202,10 @@ for (var i = 0; i < images.length; i++) {
var block = {
type: 'image-keyboard-response',
choices: [89, 78], // Y or N
prompt: '<p>Press Y to Continue. Press N to end this node of the experiment.</p>',
choices: ['y', 'n'],
prompt: '<p>Press "y" to Continue. Press "n" to end this node of the experiment.</p>',
on_finish: function(data) {
if (data.key_press == 78) {
if (data.response == 'n') {
jsPsych.endCurrentTimeline();
}
},
@ -182,8 +214,7 @@ var block = {
var after_block = {
type: 'html-keyboard-response',
stimulus: '<p>The next node</p>',
is_html: true
stimulus: '<p>The next node</p>'
}
jsPsych.init({
@ -204,9 +235,9 @@ jsPsych.endExperiment(end_message)
### Parameters
Parameter | Type | Description
--------- | ---- | -----------
end_message | string | A message to display on the screen after the experiment is over.
| Parameter | Type | Description |
| ----------- | ------ | ---------------------------------------- |
| end_message | string | A message to display on the screen after the experiment is over. |
### Return value
@ -224,11 +255,11 @@ Ends the experiment, skipping all remaining trials.
var trial = {
type: 'image-keyboard-response',
stimulus: 'image1.jpg',
choices: [89,78], // Y or N
prompt: '<p>Press Y to Continue. Press N to end the experiment</p>',
choices: ['y', 'n']
prompt: '<p>Press "y" to Continue. Press "n" to end the experiment</p>',
on_finish: function(data){
if(data.key_press == 78){
jsPsych.endExperiment('The experiment was ended by pressing N.');
if(data.response == "n"){
jsPsych.endExperiment('The experiment was ended by pressing "n".');
}
}
}
@ -243,9 +274,9 @@ jsPsych.finishTrial(data)
### Parameters
Parameter | Type | Description
----------|------|------------
data | object | The data to store for the trial.
| Parameter | Type | Description |
| --------- | ------ | -------------------------------- |
| data | object | The data to store for the trial. |
### Return value
@ -333,43 +364,41 @@ jsPsych.init(settings)
### Parameters
Parameter | Type | Description
----------|------|------------
settings | object | The settings object for initializing jsPsych. See table below.
| Parameter | Type | Description |
| --------- | ------ | ---------------------------------------- |
| settings | object | The settings object for initializing jsPsych. See table below. |
The settings object can contain several parameters. The only *required* parameter is `timeline`.
Parameter | Type | Description
--------- | ---- | -----------
timeline | array | An array containing the objects that describe the experiment timeline. See [Creating an Experiment: The Timeline](../overview/timeline.md).
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 subject 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.
exclusions | object | Specifies restrictions on the browser the subject can use to complete the experiment. See list of options below.
show_progress_bar | boolean | If true, then [a progress bar](../overview/progress-bar.md) is shown at the top of the page.
message_progress_bar | string | Message to display next to the progress bar. The default is 'Completion Progress'.
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.
show_preload_progress_bar | boolean | If true, then a progress bar is displayed while media files are automatically preloaded.
preload_audio | array | An array of audio files to preload before starting the experiment.
preload_images | array | An array of image files to preload before starting the experiment.
preload_video | array | An array of video files to preload before starting the experiment.
max_load_time | numeric | The maximum number of milliseconds to wait for content to preload. If the wait time is exceeded an error message is displayed and the experiment stops. The default value is 60 seconds.
max_preload_attempts | numeric | The maximum number of attempts to preload each file in case of an error. The default value is 10. There is a small delay of 200ms between each attempt.
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.
| Parameter | Type | Description |
| -------------------------- | -------- | ---------------------------------------- |
| timeline | array | An array containing the objects that describe the experiment timeline. See [Creating an Experiment: The Timeline](../overview/timeline.md). |
| 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 subject 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. |
| exclusions | object | Specifies restrictions on the browser the subject can use to complete the experiment. See list of options below. |
| show_progress_bar | boolean | If true, then [a progress bar](../overview/progress-bar.md) is shown at the top of the page. |
| message_progress_bar | string | Message to display next to the progress bar. The default is 'Completion Progress'. |
| 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. |
Possible values for the exclusions parameter above.
Parameter | Type | Description
--------- | ---- | -----------
min_width | numeric | The minimum width of the browser window. If the width is below this value, a message will be displayed to the subject asking them to maximize their browser window. The experiment will sit on this page until the browser window is large enough.
min_height | numeric | Same as above, but with height.
audio | boolean | Set to true to require support for the WebAudio API (used by plugins that play audio files).
| Parameter | Type | Description |
| ---------- | ------- | ---------------------------------------- |
| min_width | numeric | The minimum width of the browser window. If the width is below this value, a message will be displayed to the subject asking them to maximize their browser window. The experiment will sit on this page until the browser window is large enough. |
| min_height | numeric | Same as above, but with height. |
| audio | boolean | Set to true to require support for the WebAudio API (used by plugins that play audio files). |
### Return value
@ -437,7 +466,7 @@ var trial = {
stimulus: 'Press p to take a 30 second break. Otherwise, press c to continue immediately.',
choices: ['p','c'],
on_finish: function(data){
if(data.key_press == 80) { // 80 = p
if(data.response == "p") {
jsPsych.pauseExperiment();
setTimeout(jsPsych.resumeExperiment, 30000);
}
@ -460,11 +489,11 @@ 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.
| 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. |
### Description
@ -506,7 +535,7 @@ var trial = {
stimulus: 'Press p to take a 30 second break. Otherwise, press c to continue immediately.',
choices: ['p','c'],
on_finish: function(data){
if(data.key_press == 80) { // 80 = p
if(data.response == "p") {
jsPsych.pauseExperiment();
setTimeout(jsPsych.resumeExperiment, 30000);
}
@ -523,9 +552,9 @@ jsPsych.setProgressBar(value)
### Parameters
Parameter | Type | Description
----------|------|------------
value | numeric | Proprotion (between 0 and 1) to fill the progress bar.
| Parameter | Type | Description |
| --------- | ------- | ---------------------------------------- |
| value | numeric | Proprotion (between 0 and 1) to fill the progress bar. |
### Return value
@ -576,14 +605,16 @@ jsPsych.timelineVariable(variable, call_immediate)
### Parameters
Parameter | Type | Description
----------|------|------------
variable | string | Name of the timeline variable
call_immediate | bool | Typically this parameter is `false`, or simply ommitted. When `false`, the return value is a function that returns the timeline variable. This makes `jsPsych.timelineVariable` suitable for dynamic parameters by default. If `true` the function returns the value of the timeline variable immediately.
call_immediate | bool | This parameter is optional and can usually be omitted. It determines the return value of `jsPsych.timelineVariable`. If `true`, the function returns the _value_ of the current timeline variable. If `false`, the function returns _a function that returns the value_ of the current timeline variable. When `call_immediate` is omitted, the appropriate option is determined automatically based on the context in which this function is called. When `jsPsych.timelineVariable` is used as a parameter value, `call_immediate` will be `false`. This allows it to be used as a [dynamic trial parameter](/overview/dynamic-parameters). When `jsPsych.timelineVariable` is used inside of a function, `call_immediate` will be `true`. It is possible to explicitly set this option to `true` to force the function to immediately return the current value of the timeline variable.
### Return value
Depends on the value of `call_immediate` parameter. See description above.
Either a function that returns the value of the timeline variable, or the value of the timeline variable, depending on the context in which it is used. See `call_immediate` description above.
### Description
@ -611,6 +642,25 @@ var procedure = {
#### Invoking immediately in a function
```javascript
var trial = {
type: 'html-keyboard-response',
stimulus: function(){
return "<img style='width:100px; height:100px;' src='"+jsPsych.timelineVariable('image')+"'></img>";
}
}
var procedure = {
timeline: [trial],
timeline_variables: [
{image: 'face1.png'},
{image: 'face2.png'},
{image: 'face3.png'},
{image: 'face4.png'}
]
}
```
Prior to jsPsych v6.3.0, the `call_immediate` parameter must be set to `true` when `jsPsych.timelineVariable` is called from within a function, such as a [dynamic parameter](/overview/dynamic-parameters):
```javascript
var trial = {
type: 'html-keyboard-response',
stimulus: function(){
@ -629,7 +679,6 @@ var procedure = {
}
```
---
## jsPsych.totalTime
@ -657,3 +706,29 @@ var time = jsPsych.totalTime();
console.log(time);
```
---
## jsPsych.version
```
jsPsych.version
```
### Parameters
None.
### Return value
Returns the version number as a string.
### Description
Gets the version of jsPsych.
### Example
```javascript
var version = jsPsych.version();
console.log(version);
```

View File

@ -381,7 +381,7 @@ var too_long = jsPsych.data.get().filterCustom(function(trial){
#### .first() / .last()
Returns a DataCollection containing the first/last *n* trials.
Returns a DataCollection containing the first/last *n* trials. If *n* is greater than the number of trials in the DataCollection, then these functions will return an array of length equal to the number of trials. If there are no trials in the DataCollection, then these functions will return an empty array. If the *n* argument is omitted, then the functions will use the default value of 1. If *n* is zero or a negative number, then these functions will throw an error.
```js
var first_trial = jsPsych.data.get().first(1);

View File

@ -2,39 +2,6 @@
The pluginAPI module contains functions that are useful when developing new plugins.
---
## jsPsych.pluginAPI.autoPreload
```
jsPsych.pluginAPI.autoPreload(timeline, callback)
```
### Parameters
Parameter | Type | Description
----------|------|------------
timeline | TimelineNode object | A TimelineNode object that contains an arbitrary set of trials.
callback | function | A function to execute when loading is complete
### Return value
Returns nothing.
### Description
Attempts to preload all image files and audio files that will be used to run the trials on the timeline. Content will only preload from plugins that have used the `registerPreload` method to define the media types of their parameters.
The callback function executes once all of the files are preloaded.
This method is used internally by the core jsPsych code. It is not recommended that you call it manually.
### Examples
```javascript
// you probably shouldn't use this method
```
---
## jsPsych.pluginAPI.cancelAllKeyboardResponses
@ -118,100 +85,7 @@ Returns nothing.
Clears any pending timeouts that were set using jsPsych.pluginAPI.setTimeout()
---
## jsPsych.pluginAPI.compareKeys
```
jsPsych.pluginAPI.compareKeys(key1, key2)
```
### Parameters
Parameter | Type | Description
----------|------|------------
key1 | string or numeric | The representation of a key, either string or keycode
key2 | string or numeric | The representation of a key, either string or keycode
### Return value
Returns true if keycodes or strings refer to the same key, regardless of type.
### Description
Compares two keys to see if they are the same, ignoring differences in representational type.
### Examples
```javascript
jsPsych.pluginAPI.compareKeys('a', 65);
// returns true
jsPsych.pluginAPI.convertKeyCharacterToKeyCode('space', 31)
// returns false
```
---
## jsPsych.pluginAPI.convertKeyCharacterToKeyCode
```
jsPsych.pluginAPI.convertKeyCharacterToKeyCode(character)
```
### Parameters
Parameter | Type | Description
----------|------|------------
character | string | The string representation of keyboard key.
### Return value
Returns the numeric keycode associated with the `character` parameter.
### Description
Converts between the string representation of a key and the numeric key code associated with that key.
### Examples
```javascript
var keycode = jsPsych.pluginAPI.convertKeyCharacterToKeyCode('a')
// keycode is 65
keycode = jsPsych.pluginAPI.convertKeyCharacterToKeyCode('space')
// keycode is 32
```
---
## jsPsych.pluginAPI.convertKeyCodeToKeyCharacter
```
jsPsych.pluginAPI.convertKeyCodeToKeyCharacter(character)
```
### Parameters
Parameter | Type | Description
----------|------|------------
code | numeric | The numeric representation of keyboard key.
### Return value
Returns the string representation of the key associated with the `code` parameter.
### Description
Converts between the numeric key code of a key and the string representation associated with that key.
### Examples
```javascript
var keycode = jsPsych.pluginAPI.convertKeyCharacterToKeyCode(65)
// key is 'a'
keycode = jsPsych.pluginAPI.convertKeyCharacterToKeyCode(32)
// keycode is 'space'
```
---
## jsPsych.pluginAPI.getAudioBuffer
```
@ -230,7 +104,7 @@ Returns buffered audio file for playback. If the browser supports it the buffer
### Description
Gets an AudioBuffer that can be played with the WebAudio API or an Audio object that can be played with HTML5 Audio. The file must be preloaded with `preloadAudioFiles` or the automatic preload (`autoPreload`).
Gets an AudioBuffer that can be played with the WebAudio API or an Audio object that can be played with HTML5 Audio. The file must be preloaded with the `preload` plugin.
### Examples
@ -243,6 +117,51 @@ startTime = context.currentTime;
source.start(startTime);
```
## jsPsych.pluginAPI.getAutoPreloadList
```
jsPsych.pluginAPI.getAutoPreloadList(timeline)
```
### Parameters
Parameter | Type | Description
----------|------|------------
timeline | array | An array containing the trial object(s) from which a list of media files should be automatically generated. This array can contain the entire experiment timeline, or any individual parts of a larger timeline, such as specific timeline nodes and trial objects.
### Return value
An object with properties for each media type: `images`, `audio`, and `video`. Each property contains an array of the unique files of that media type that were automatically extracted from the timeline. If no files are found in the timeline for a particular media type, then the array will be empty for that type.
### Description
This method is used to automatically generate lists of unique image, audio, and video files from a timeline. It is used by the `preload` plugin to generate a list of to-be-preloaded files based on the trials passed to the `trials` parameter and/or the experiment timeline passed to `jsPsych.init` (when `auto_preload` is true). It can be used in custom plugins and experiment code to generate a list of audio/image/video files, based on a timeline.
This function will only return files from plugins that have used the `registerPreload` method to define the media types of their parameters, and only when the trial's parameter value is not a function. When a file path is returned to the trial parameter from a function (including by `jsPsych.timelineVariable` function), or when the file path is embedded in an HTML string, that file will not be detected by the `getAutoPreloadList` method. In these cases, the file should be preloaded manually. See [Media Preloading](../overview/media-preloading.md) for more information.
### Example
```javascript
var audio_trial = {
type: 'audio-keyboard-response'
stimulus: 'file.mp3'
}
var image_trial = {
type: 'image-keyboard-response'
stimulus: 'file.png'
}
var video_trial = {
type: 'video-keyboard-response'
stimulus: 'file.mp4'
}
var timeline = [audio_trial, image_trial, video_trial];
jsPsych.pluginAPI.getAutoPreloadList(timeline);
```
---
## jsPsych.pluginAPI.getKeyboardResponse
@ -293,13 +212,13 @@ jsPsych.pluginAPI.getKeyboardResponse({
});
```
#### Get a responses from a key until the letter Q is pressed
#### Get a responses from a key until the letter q is pressed
```javascript
var after_response = function(info){
alert('You pressed key '+info.key+' after '+info.rt+'ms');
if(info.key == 81){ // the key code for 'Q' is 81.
if(info.key == 'q'){ /
jsPsych.pluginAPI.cancelKeyboardResponse(listener);
}
}
@ -313,10 +232,10 @@ var listener = jsPsych.pluginAPI.getKeyboardResponse({
```
---
## jsPsych.pluginAPI.preloadAudioFiles
## jsPsych.pluginAPI.preloadAudio
```
jsPsych.pluginAPI.preloadAudioFiles(files, callback_complete, callback_load)
jsPsych.pluginAPI.preloadAudio(files, callback_complete, callback_load, callback_error)
```
### Parameters
@ -325,7 +244,8 @@ Parameter | Type | Description
----------|------|------------
files | array | An array of audio file paths to load. The array can be nested (e.g., if images are in multiple arrays to help sort by condition or task).
callback_complete | function | A function to execute when all the files have been loaded.
callback_load | function | A function to execute after each file has been loaded. A single parameter is passed to this function which contains the number of files that have been loaded so far.
callback_load | function | A function to execute after a single file has been loaded. A single parameter is passed to this function which is the file source (string) that has loaded.
callback_error | function | A function to execute after a single file has produced an error. A single parameter is passed to this function which is the file source (string) that produced the error.
### Return value
@ -333,11 +253,11 @@ Returns nothing.
### Description
Use this function to preload audio files that are not part of a plugin with automatic preloading. Audio files in official plugins will automatically preload. See [Media Preloading](../overview/media-preloading.md) for more information.
This function is used to preload audio files. It is used by the `preload` plugin, and could be called directly to preload audio files in custom plugins or experiment. See [Media Preloading](../overview/media-preloading.md) for more information.
It is possible to run this function without specifying a callback function. However, in this case the code will continue executing while the files are loaded. Thus, it is possible that an audio file would be required for playing before it is done preloading. The `callback_complete` function will only execute after all the audio files are loaded, and can be used to control the flow of the experiment (e.g., by starting the experiment in the `callback_complete` function).
The `callback_load` function can be used to indicate progress. See example below.
The `callback_load` and `callback_error` functions are called after each file has either loaded or produced an error, so these functions can also be used to monitor loading progress. See example below.
### Examples
@ -346,7 +266,11 @@ The `callback_load` function can be used to indicate progress. See example below
var sounds = ['file1.mp3', 'file2.mp3', 'file3.mp3'];
jsPsych.pluginAPI.preloadAudioFiles(sounds, function(){ startExperiment(); });
jsPsych.pluginAPI.preloadAudio(sounds,
function(){ startExperiment(); },
function(file){ console.log('file loaded: ', file); }
function(file){ console.log('error loading file: ', file); }
);
function startExperiment(){
jsPsych.init({
@ -360,11 +284,13 @@ function startExperiment(){
```javascript
var sounds = ['file1.mp3', 'file2.mp3', 'file3.mp3'];
var n_loaded = 0;
jsPsych.pluginAPI.preloadAudioFiles(sounds, function(){ startExperiment(); }, function(nLoaded) { updateLoadedCount(nLoaded); });
jsPsych.pluginAPI.preloadAudio(sounds, function(){ startExperiment(); }, function(file) { updateLoadedCount(file); });
function updateLoadedCount(nLoaded){
var percentcomplete = nLoaded / sounds.length * 100;
function updateLoadedCount(file){
n_loaded++;
var percentcomplete = n_loaded / sounds.length * 100;
// could put something fancier here, like a progress bar
// or updating text in the DOM.
@ -378,12 +304,11 @@ function startExperiment(){
}
```
---
## jsPsych.pluginAPI.preloadImages
```
jsPsych.pluginAPI.preloadImages(images, callback_complete, callback_load)
jsPsych.pluginAPI.preloadImages(images, callback_complete, callback_load, callback_error)
```
### Parameters
@ -392,7 +317,8 @@ Parameter | Type | Description
----------|------|------------
images | array | An array of image paths to load. The array can be nested (e.g., if images are in multiple arrays to help sort by condition or task).
callback_complete | function | A function to execute when all the images have been loaded.
callback_load | function | A function to execute after each image has been loaded. A single parameter is passed to this function which contains the number of images that have been loaded so far.
callback_load | function | A function to execute after a single file has been loaded. A single parameter is passed to this function which is the file source (string) that has loaded.
callback_error | function | A function to execute after a single file has produced an error. A single parameter is passed to this function which is the file source (string) that produced the error.
### Return value
@ -400,11 +326,11 @@ Returns nothing.
### Description
Use this function to preload image files that are not part of a plugin with automatic preloading. Image files in official plugins will automatically preload. See [Media Preloading](../overview/media-preloading.md) for more information.
This function is used to preload image files. It is used by the `preload` plugin, and could be called directly to preload image files in custom plugins or experiment code. See [Media Preloading](../overview/media-preloading.md) for more information.
It is possible to run this function without specifying a callback function. However, in this case the code will continue executing while the images are loaded. Thus, it is possible that an image would be required for display before it is done preloading. The `callback_complete` function will only execute after all the images are loaded, and can be used to control the flow of the experiment (e.g., by starting the experiment in the `callback_complete` function).
The `callback_load` function can be used to indicate progress, if the number of images to be loaded is known ahead of time. See example below.
The `callback_load` and `callback_error` functions are called after each file has either loaded or produced an error, so these functions can also be used to monitor loading progress. See example below.
### Examples
@ -413,7 +339,11 @@ The `callback_load` function can be used to indicate progress, if the number of
var images = ['img/file1.png', 'img/file2.png', 'img/file3.png'];
jsPsych.pluginAPI.preloadImages(images, function(){ startExperiment(); });
jsPsych.pluginAPI.preloadImages(images,
function(){ startExperiment(); },
function(file){ console.log('file loaded: ', file); }
function(file){ console.log('error loading file: ', file); }
);
function startExperiment(){
jsPsych.init({
@ -427,11 +357,13 @@ function startExperiment(){
```javascript
var images = ['img/file1.png', 'img/file2.png', 'img/file3.png'];
var n_loaded = 0;
jsPsych.pluginAPI.preloadImages(images, function(){ startExperiment(); }, function(nLoaded) { updateLoadedCount(nLoaded); });
jsPsych.pluginAPI.preloadImages(images, function(){ startExperiment(); }, function(file) { updateLoadedCount(file); });
function updateLoadedCount(nLoaded){
var percentcomplete = nLoaded / images.length * 100;
function updateLoadedCount(file){
n_loaded++;
var percentcomplete = n_loaded / images.length * 100;
// could put something fancier here, like a progress bar
// or updating text in the DOM.
@ -445,11 +377,84 @@ function startExperiment(){
}
```
---
## jsPsych.pluginAPI.preloadVideo
```
jsPsych.pluginAPI.preloadVideo(video, callback_complete, callback_load, callback_error)
```
### Parameters
Parameter | Type | Description
----------|------|------------
video | array | An array of video paths to load. The array can be nested (e.g., if videos are in multiple arrays to help sort by condition or task).
callback_complete | function | A function to execute when all the videos have been loaded.
callback_load | function | A function to execute after a single file has been loaded. A single parameter is passed to this function which is the file source (string) that has loaded.
callback_error | function | A function to execute after a single file has produced an error. A single parameter is passed to this function which is the file source (string) that produced the error.
### Return value
Returns nothing.
### Description
This function is used to preload video files. It is used by the `preload` plugin, and could be called directly to preload video files in custom plugins or experiment code. See [Media Preloading](../overview/media-preloading.md) for more information.
It is possible to run this function without specifying a callback function. However, in this case the code will continue executing while the videos are loaded. Thus, it is possible that a video would be requested before it is done preloading. The `callback_complete` function will only execute after all the videos are loaded, and can be used to control the flow of the experiment (e.g., by starting the experiment in the `callback_complete` function).
The `callback_load` and `callback_error` functions are called after each file has either loaded or produced an error, so these functions can also be used to monitor loading progress. See example below.
### Examples
#### Basic use
```javascript
var videos = ['vid/file1.mp4', 'vid/file2.mp4', 'vid/file3.mp4'];
jsPsych.pluginAPI.preloadVideo(videos,
function(){ startExperiment(); },
function(file){ console.log('file loaded: ', file); }
function(file){ console.log('error loading file: ', file); }
);
function startExperiment(){
jsPsych.init({
timeline: exp
});
}
```
#### Show progress of loading
```javascript
var videos = ['vid/file1.mp4', 'vid/file2.mp4', 'vid/file3.mp4'];
var n_loaded = 0;
jsPsych.pluginAPI.preloadVideo(videos, function(){ startExperiment(); }, function(file) { updateLoadedCount(file); });
function updateLoadedCount(file){
n_loaded++;
var percentcomplete = n_loaded / videos.length * 100;
// could put something fancier here, like a progress bar
// or updating text in the DOM.
console.log('Loaded '+percentcomplete+'% of videos');
}
function startExperiment(){
jsPsych.init({
timeline: exp
});
}
```
---
## jsPsych.pluginAPI.registerPreload
```
jsPsych.pluginAPI.registerPreload(plugin_name, parameter, media_type, conditional_function)
jsPsych.pluginAPI.registerPreload(plugin_name, parameter, media_type)
```
### Parameters
@ -458,8 +463,7 @@ Parameter | Type | Description
----------|------|------------
plugin_name | string | The name of the plugin. e.g., 'image-keyboard-response'.
parameter | string | The name of the parameter that is a media file. e.g., 'stimulus'
media_type | string | The type of media, either 'image' or 'audio'.
conditional_function | function | Only run the preload for a trial if this function returns true, or if this function does not exist.
media_type | string | The type of media, either 'image', 'audio' or 'video'.
### Return value
@ -469,13 +473,12 @@ Nothing.
Use this method in a plugin file to mark a parameter as containing an element that should be preloaded. The method should be called in the plugin file such that it gets called when the file is loaded.
The `conditional_function` function is passed a single argument containing the trial object.
### Example
For an example, see the [image-keyboard-response](https://github.com/jodeleeuw/jsPsych/blob/master/plugins/jspsych-image-keyboard-response.js) and [audio-keyboard-response](https://github.com/jodeleeuw/jsPsych/blob/master/plugins/jspsych-audio-keyboard-response.js) plugins.
For an example, see the [image-keyboard-response](https://github.com/jspsych/jsPsych/blob/master/plugins/jspsych-image-keyboard-response.js) and [audio-keyboard-response](https://github.com/jspsych/jsPsych/blob/master/plugins/jspsych-audio-keyboard-response.js) plugins.
---
## jsPsych.pluginAPI.setTimeout
```

View File

@ -12,11 +12,11 @@ jsPsych.randomization.factorial(factors, repetitions, unpack)
### Parameters
Parameter | Type | Description
----------|------|------------
factors | object | The `factors` object should contain a property for each different factor. Each property-factor should have a value of an array, with each element of the array corresponding to a level of the factor.
repetitions | integer | The number of times to repeat each unique combination of the factors in the output sample.
unpack | boolean | If `true` then the output will be an object with a property for each factor in the original `factors` object. The value of each property-factor will be an array containing the levels of the factor in a random order. The order will be consistent across each property-factor (e.g., the first element of each property-factor will specify one unique combination of the factors). If `false`, then the return value will be an array of objects where each property-factor contains only a single value.
| Parameter | Type | Description |
| ----------- | ------- | ---------------------------------------- |
| factors | object | The `factors` object should contain a property for each different factor. Each property-factor should have a value of an array, with each element of the array corresponding to a level of the factor. |
| repetitions | integer | The number of times to repeat each unique combination of the factors in the output sample. |
| unpack | boolean | If `true` then the output will be an object with a property for each factor in the original `factors` object. The value of each property-factor will be an array containing the levels of the factor in a random order. The order will be consistent across each property-factor (e.g., the first element of each property-factor will specify one unique combination of the factors). If `false`, then the return value will be an array of objects where each property-factor contains only a single value. |
### Return value
@ -99,9 +99,9 @@ jsPsych.randomization.randomID(length)
### Parameters
Parameter | Type | Description
----------|------|------------
length | integer | The length of the randomly generated ID
| Parameter | Type | Description |
| --------- | ------- | --------------------------------------- |
| length | integer | The length of the randomly generated ID |
### Return value
@ -132,11 +132,11 @@ jsPsych.randomization.repeat(array, repetitions, unpack)
### Parameters
Parameter | Type | Description
----------|------|------------
array | array | The array of values to randomize & repeat.
repetitions | integer or array | The number of times to repeat each element of the `array` in the final sample. If this parameter is defined as an integer, then each element of `array` is repeated the same number of times. This parameter can also be an array of the same length as `array`, in which case each element of `array` will be repeated the number of times defined in the corresponding position of the `repetitions` array.
unpack | boolean | If each element of `array` is an object with an equivalent set of properties, then setting `unpack` to `true` will make the return value an object with a property for each of the unique properties among the elements of the `array`. Each property in the output object will be an array containing the values for that property in the randomized order. The order will be consistent across properties. If this is `false` then the output is just an array containing a randomized order of the original `array` elements.
| Parameter | Type | Description |
| ----------- | ---------------- | ---------------------------------------- |
| array | array | The array of values to randomize & repeat. |
| repetitions | integer or array | The number of times to repeat each element of the `array` in the final sample. If this parameter is defined as an integer, then each element of `array` is repeated the same number of times. This parameter can also be an array of the same length as `array`, in which case each element of `array` will be repeated the number of times defined in the corresponding position of the `repetitions` array. |
| unpack | boolean | If each element of `array` is an object with an equivalent set of properties, then setting `unpack` to `true` will make the return value an object with a property for each of the unique properties among the elements of the `array`. Each property in the output object will be an array containing the values for that property in the randomized order. The order will be consistent across properties. If this is `false` then the output is just an array containing a randomized order of the original `array` elements. |
### Return value
@ -176,19 +176,19 @@ var shuffledArray = jsPsych.randomization.repeat(myArray, 2);
var trial1 = {
stimulus: 'img/faceA.jpg',
correct_key: 80,
correct_key: 'p',
person_name: 'Joe'
}
var trial2 = {
stimulus: 'img/faceB.jpg',
correct_key: 80,
correct_key: 'p',
person_name: 'Fred'
}
var trial3 = {
stimulus: 'img/faceC.jpg',
correct_key: 81,
correct_key: 'q',
person_name: 'Mary'
}
@ -204,19 +204,19 @@ var shuffledArray = jsPsych.randomization.repeat(myArray, 2);
var trial1 = {
stimulus: 'img/faceA.jpg',
correct_key: 80,
correct_key: 'p',
person_name: 'Joe'
}
var trial2 = {
stimulus: 'img/faceB.jpg',
correct_key: 80,
correct_key: 'p',
person_name: 'Fred'
}
var trial3 = {
stimulus: 'img/faceC.jpg',
correct_key: 81,
correct_key: 'q',
person_name: 'Mary'
}
@ -226,8 +226,8 @@ var shuffledArray = jsPsych.randomization.repeat(myArray, 2, true);
/*
output: shuffledArray = {
stimulus: ['img/faceB.jpg','img/faceA.jpg','img/faceC.jpg','img/faceA.jpg','img/faceC.jpg','img/faceB.jpg'],
correct_key: [80, 80, 81, 80, 81, 80],
person_name: ['Fred','Joe', 'Mary', 'Joe', 'Mary', 'Fred']
correct_key: ['p', 'p', 'q', 'p', 'q', 'p'],
person_name: ['Fred', 'Joe', 'Mary', 'Joe', 'Mary', 'Fred']
}
*/
```
@ -240,11 +240,11 @@ jsPsych.randomization.sampleWithReplacement(array, sampleSize, weights)
### Parameters
Parameter | Type | Description
----------|------|------------
array | array | The array of values to sample from
sampleSize | numeric | The number of samples to draw
weights | array | The relative weight of each element in `array`. This array is normalized, so the values do not need to sum to 1. The length must match the length of `array`.
| Parameter | Type | Description |
| ---------- | ------- | ---------------------------------------- |
| array | array | The array of values to sample from |
| sampleSize | numeric | The number of samples to draw |
| weights | array | The relative weight of each element in `array`. This array is normalized, so the values do not need to sum to 1. The length must match the length of `array`. |
### Return value
@ -285,10 +285,10 @@ jsPsych.randomization.sampleWithoutReplacement(array, sampleSize)
### Parameters
Parameter | Type | Description
----------|------|------------
array | array | The array of values to sample from
sampleSize | numeric | The number of samples to draw
| Parameter | Type | Description |
| ---------- | ------- | ---------------------------------- |
| array | array | The array of values to sample from |
| sampleSize | numeric | The number of samples to draw |
### Return value
@ -319,9 +319,9 @@ jsPsych.randomization.shuffle(array)
### Parameters
Parameter | Type | Description
----------|------|------------
array | array | The array of values to shuffle
| Parameter | Type | Description |
| --------- | ----- | ------------------------------ |
| array | array | The array of values to shuffle |
### Return value
@ -352,10 +352,10 @@ jsPsych.randomization.shuffleNoRepeats(array, equalityTest)
### Parameters
Parameter | Type | Description
----------|------|------------
array | array | The array of values to shuffle
equalityTest | function | A function to use to evaluate the equality of neighbors in the array. The function should accept two parameters, which are the two elements to be tested. It should return `true` if they are equal and `false` if not. The default function, if none is specified, is to use the `===` operator. This will work for primitive values, but fail for Objects and Arrays. An example function is given below in the examples.
| Parameter | Type | Description |
| ------------ | -------- | ---------------------------------------- |
| array | array | The array of values to shuffle |
| equalityTest | function | A function to use to evaluate the equality of neighbors in the array. The function should accept two parameters, which are the two elements to be tested. It should return `true` if they are equal and `false` if not. The default function, if none is specified, is to use the `===` operator. This will work for primitive values, but fail for Objects and Arrays. An example function is given below in the examples. |
### Return value

View File

@ -13,7 +13,7 @@ jsPsych.turk.submitToTurk(data)
Parameter | Type | Description
----------|------|------------
data | object | The `data` parameter is an object of `key: value` pairs. Any pairs in the `data` parameter will be saved by Mechanical Turk, and can be downloaded in a CSV file through the Mechanical Turk interface.
data | object | The `data` parameter is an object of `key: value` pairs. Any pairs in the `data` parameter will be saved by Mechanical Turk, and can be downloaded in a CSV file through the Mechanical Turk interface. **Important**: the `data` parameter must contain at least one `key: value` pair, even just a dummy value, or the HIT will not be submitted correctly.
### Return value

View File

@ -0,0 +1,83 @@
# Extensions
Extensions are jsPsych modules that can interface with any plugin to extend the functionality of the plugin. A canonical example of an extension is eye tracking. An eye tracking extension allows a plugin to gather gaze data and add it to the plugin's data object.
## 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()`.
```html
<head>
<script src="jspsych/jspsych.js"></script>
<script src="jspsych/extensions/some-extension.js"></script>
</head>
```
```js
jsPsych.init({
timeline: [...],
extensions: [
{type: 'some-extension', params: {...} }
]
})
```
To enable an extension during a trial, add the extension to the `extensions` list for the trial. Some extensions may also support or require an object of parameters to configure the extension:
```js
var trial = {
extensions: [
{type: 'some-extension', params: {...} }
]
}
```
## List of Extensions
Extension | Description
------ | -----------
[jspsych&#8209;ext&#8209;webgazer.js](/extensions/jspsych-ext-webgazer.md) | Enables eye tracking using the [WebGazer](https://webgazer.cs.brown.edu/) library.
## Writing an Extension
To create a new extension you must create an object that supports a few event callbacks. A barebones extension file looks like this:
```js
jsPsych.extensions['new-extension'] = (function () {
var extension = {};
extension.initialize = function(params){
// params are passed from the extensions parameter in jsPsych.init
}
extension.on_start = function(params){
// params are passed from the extensions parameter in the trial object
}
extension.on_load = function(params){
// params are passed from the extensions parameter in the trial object
}
extension.on_finish = function(params){
// params are passed from the extensions parameter in the trial object
return {
// any data that the extension returns here will be added to the trial data
}
}
return extension;
});
```
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.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_load` is called after `plugin.trial` has executed, which is typically when the plugin has finished executing initial DOM-modifying code and has set up various event listeners. This is where the extension can begin actively interacting with the DOM and recording data. 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_finish` is called after the plugin completes. This can be used for any teardown at the end of the trial. This method should return an object of data to append to the plugin's data. Note that this event fires *before* the `on_finish` event for the plugin, so data added by the extension is accessible in any trial `on_finish` event handlers. 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.
The extension can also include any additional methods that are necessary for interacting with it. See the [webgazer extension](/extensions/jspsych-ext-webgazer.md) for an example.

View File

@ -0,0 +1,106 @@
# jspsych-ext-webgazer
This extension supports eye tracking through the [WebGazer](https://webgazer.cs.brown.edu/) library. For a narrative description of how to use this extension see the [eye tracking overview](/overview/eye-tracking.md).
## Parameters
### Initialization Parameters
Initialization parameters can be set when calling `jsPsych.init()`
```js
jsPsych.init({
extensions: [
{type: 'webgazer', params: {...}}
]
})
```
Parameter | Type | Default Value | Description
----------|------|---------------|------------
webgazer | object | `undefined` | You can explicitly pass a reference to a loaded instance of the webgazer.js library. If no explicit reference is passed then the extension will look for a global `webgazer` object. If you are loading webgazer.js via a `<script>` tag you do not need to set this parameter in most circumstances.
round_predictions | bool | true | Whether to round the `x`,`y` coordinates predicted by WebGazer to the nearest whole number. This *greatly* reduces the size of the data, as WebGazer records data to 15 decimal places by default. Given the noise of the system, there's really no need to record data to this level of precision.
### Trial Parameters
Trial parameters can be set when adding the extension to a trial object.
```js
var trial = {
type: '...',
extensions: [
{type: 'webgazer', params: {...}}
]
}
```
Parameter | Type | Default Value | Description
----------|------|---------------|------------
targets | array | [] | A list of elements on the page that you would like to record the coordinates of for comparison with the WebGazer data. Each entry in the array should be a valid [CSS selector string](https://www.w3schools.com/cssref/css_selectors.asp) that identifies the element. The selector string should be valid for exactly one element on the page. If the selector is valid for more than one element then only the first matching element will be recorded.
## Data Generated
Name | Type | Value
-----|------|------
webgazer_data | array | An array of objects containing gaze data for the trial. Each object has an `x`, a `y`, and a `t` property. The `x` and `y` properties specify the gaze location in pixels and `t` specifies the time in milliseconds since the start of the trial.
webgazer_targets | array | An array of objects contain the pixel coordinates of elements on the screen specified by the `.targets` parameter. Each object contains a `selector` property, containing the CSS selector string used to find the element, plus `top`, `bottom`, `left`, and `right` parameters which specify the [bounding rectangle](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect) of the element.
## Functions
In addition to the jsPsych webgazer-* plugins, the jsPsych webgazer extension provides a set of functions that allow the researcher to interact more directly with WebGazer. These functions can be called at any point during an experiment, and are crucial for building trial plugins that interact with WebGazer. All of the functions below must be prefixed with `jsPsych.extensions.webgazer` (e.g. `jsPsych.extensions.webgazer.faceDetected()`).
### faceDetected()
Returns `true` if WebGazer is ready to make predictions (`webgazer.getTracker().predictionReady` is `true`).
### showPredictions()
Turns on WebGazer's real-time visualization of predicted gaze location.
### hidePredictions()
Turns off WebGazer's real-time visualization of predicted gaze location.
### showVideo()
Turns on a display of the webcam image, guiding box for positioning the face, and WebGazer's estimate of the location of facial landmarks.
### hideVideo()
Turns off the camera display.
### resume()
Turns on gaze prediction. The extension will automatically handle this for you in most cases. You probably only need to use this if you are writing your own plugin that interfaces directly with WebGazer.
### pause()
Turns off gaze prediction. The extension will automatically handle this for you in most cases. You probably only need to use this if you are writing your own plugin that interfaces directly with WebGazer.
### startMouseCalibration()
Turns on mouse movement and mouse clicks as calibration events. While the `webgazer-calibration` plugin can also be used to run a parmeterized calibration routine, this calibration function call allows you to continuously calibrate WebGazer to any mouse movements or clicks throughout the experiment. For example, any *-button-response trial would also function as a WebGazer calibration event.
### stopMouseCalibration()
Stops WebGazer from using mouse movements and mouse clicks as calibration events.
### calibratePoint(x, y)
Instructs WebGazer to register the location `x`, `y` (in screen pixel coordinates) as a calibration event. Can be used for passive viewing calibration, i.e., instructing participants to fixate at a particular location.
### setRegressionType(regression_type)
Change the method that WebGazer is using to perform feature -> location regression. Valid options are `ridge`, `weightedRidge`, and `threadedRidge`. See the WebGazer docs for more information about these options.
The extension uses the default mode specified by WebGazer (currently `ridge`).
### getCurrentPrediction()
Get the current predicted gaze location from WebGazer. Returns an object with `x`, `y`, and `eyeFeature` properties. This function is asynchronus, so proper use requires either the `await` keyword in the context of another `async function` or using `.then()`.
```js
jsPsych.extensions.webgazer.getCurrentPrediction().then(function(data){
console.log(`Currently looking at coordinate ${data.x}, ${data.y}`)
});
```

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 89 KiB

After

Width:  |  Height:  |  Size: 69 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 110 KiB

View File

@ -0,0 +1,35 @@
# Browser and Device Support
## Desktop and Laptop Browsers
**Supported**
jsPsych supports recent versions of the four most commonly-used web browsers:
* Chrome
* Firefox
* Safari
* Edge
This means that jsPsych _should_ work on these browsers. If something doesn't work as you expect on one of the browsers above, it might be a bug that should be fixed. You can search for and report bugs on the [jsPsych GitHub Issues page](https://github.com/jspsych/jsPsych/issues). We're very grateful for anyone who takes the time to report bugs - it helps improve the library for everyone!
**Unsupported**
There are many other web browsers that are available, but that are not commonly used. The most well-known of these are Internet Explorer and Opera. jsPsych is not tested on these and other browsers not listed in the Supported section above. jsPsych experiments _might_ work in these browsers, but they _might not_. If you want to give participants the option to use unsupported browsers, then we recommend carefully testing your experiment to make sure that everything works as expected. Otherwise, we suggest asking your participants to only use a supported browser, or incorporating browser, device, and/or feature checks at the start of your experiment. jsPsych offers built-in methods for [exclusion based on minimum browser size and WebAudio API compatibility](exclude-browser.md). You can incorporate other browser/device/feature checks into your experiment by adding custom JavaScript code.
## Mobile Devices
In general, jsPsych experiments can be run on mobile devices (smartphones and tablets). However, certain plugins will not work on mobile. For instance, any plugin that requires a keyboard response without a text input box, such as the *-keyboard-response plugins, will not work. Even plugins that do work on mobile might work differently than they do on desktop and laptop computers. For instance, on mobile devices, a text input box will cause an on-screen keyboard to pop up, which affects the visible content on the screen.
If you plan to run an experiment that allows people to use mobile devices, we recommend doing some extra testing to make sure that everything works as expected. In particular, you may want to check that:
* Font sizes are readable on smaller screens
* Stimuli sizes are large enough and appropriate for the task
* Page is laid out as intended (e.g. elements are centered and do not overlap)
* Response options are touchscreen-friendly (e.g. buttons rather than key presses)
* Response options (e.g. buttons, text boxes, radio buttons) are large enough and far enough apart to be easily selected with a finger tap
It's possible to use your browser's developer tools to emulate mobile devices ([this page shows how to do it in Chrome](https://developers.google.com/web/tools/chrome-devtools/device-mode)), which is useful for getting a sense of how your experiment will look on mobile devices. Just be aware that there are limitations to emulator tools, and there are some aspects of mobile devices/browsers that a desktop browser will not be able to simulate.
## Mobile Browsers
The browser options for mobile phones and tablets are slightly different than those for desktop and laptop computers. In addition to mobile versions of Chrome, Firefox, Safari, and Edge, other notable mobile browsers include Opera Mobile, Samsung Internet, UC Browser, and Dolphin. Because of the greater diversity of mobile browsers and volatility in their usage statistics, jsPsych does not officially support any particular set of mobile browsers. However, we do anticipate that most experiments should work in most mobile browsers, especially the mobile versions of browsers that we do support in Desktop mode. If you run into a problem using jsPsych in mobile browsers, please report it on the [jsPsych GitHub Issues page](https://github.com/jspsych/jsPsych/issues)! We do our best to fix browser incompatibilities that are not specific to a single experiment.

View File

@ -46,7 +46,7 @@ var trial = {
type: 'image-keyboard-response',
stimulus: 'imgA.png',
on_finish: function(data) {
if(data.key_press == 85){
if(data.response == 'j'){
data.correct = true;
} else {
data.correct = false;
@ -105,6 +105,50 @@ var trial = {
---
## on_timeline_finish
The `on_timeline_finish` callback can be declared in a timeline node. The callback will be triggered when the timeline ends during the experiment. If `timeline_variables`, `conditional_function`, `loop_function`, or `sample` options are used, this function will execute when all trials have finished. If a `loop_function` is used, then this `on_timeline_finish` function will be triggered before the loop function. If the `repetitions` option is used, this function will be triggered at the end of every repetition.
#### Sample use
```javascript
var procedure = {
timeline: [trial1, trial2],
timeline_variables: [
{ stimulus: 'person-1.jpg' },
{ stimulus: 'person-2.jpg' },
{ stimulus: 'person-3.jpg' },
{ stimulus: 'person-4.jpg' }
],
on_timeline_finish: function() {
console.log('This timeline has finished.');
},
loop_function: function() {
console.log('This loop function will execute after on_timeline_finish.');
return false;
}
}
```
---
## on_timeline_start
The `on_timeline_start` callback can be declared in a timeline node. The callback will be triggered when the timeline starts during the experiment, including when `timeline_variables`, `loop_function`, or `sample` options are used. If a `conditional_function` is used, then the conditional function will execute first, and the `on_timeline_start` function will only execute if the conditional function returns `true`. If the `repetitions` option is used, this function will be triggered at the start of every repetition.
#### Sample use
```javascript
var procedure = {
timeline: [trial1, trial2],
conditional_function: function() {
console.log('This conditional function will execute first.')
return true;
},
on_timeline_start: function() {
console.log('This timeline has started');
}
}
```
---
## 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.

View File

@ -61,7 +61,7 @@ var trial = {
type: 'image-keyboard-response',
stimulus: 'imgA.jpg',
on_finish: function(data){
if(data.key_press == 65){
if(data.response == 'j'){
data.correct = true;
} else {
data.correct = false;

View File

@ -0,0 +1,147 @@
# Dynamic parameters
Most trial parameters can also be specified as functions. In a typical declaration of a jsPsych trial, parameters are known at the start of the experiment. This makes it impossible to alter the content of the trial based on the outcome of previous trials. However, **when functions are used as the parameter value, the function is evaluated right before the trial starts, and the return value of the function is used as the parameter value for that trial**. This enables dynamic updating of the parameter based on data that a subject has generated or any other information that you do not know in advance.
## Examples
### Providing Feedback
Here is a sketch of how this functionality could be used to display feedback to a subject in the Flanker Task.
```javascript
var timeline = [];
var trial = {
type: 'html-keyboard-response',
stimulus: '<<<<<',
choices: ['f','j'],
data: {
stimulus_type: 'congruent',
target_direction: 'left'
},
on_finish: function(data){
// Score the response as correct or incorrect.
if(data.response == "f"){
data.correct = true;
} else {
data.correct = false;
}
}
}
var feedback = {
type: 'html-keyboard-response',
stimulus: function(){
// The feedback stimulus is a dynamic parameter because we can't know in advance whether
// the stimulus should be 'correct' or 'incorrect'.
// Instead, this function will check the accuracy of the last response and use that information to set
// the stimulus value on each trial.
var last_trial_correct = jsPsych.data.get().last(1).values()[0].correct;
if(last_trial_correct){
return "<p>Correct!</p>"; // the parameter value has to be returned from the function
} else {
return "<p>Wrong.</p>"; // the parameter value has to be returned from the function
}
}
}
timeline.push(trial, feedback);
```
### Randomizing a parameter value
Here's an example of using a dynamic parameter to randomize the inter-trial interval (ITI) duration. This time, the dynamic parameter is created using a named function instead of an anonymous function.
```js
var random_duration = function() {
var rand_dur = jsPsych.randomization.sampleWithoutReplacement([500,600,700,800],1)[0];
return rand_dur;
}
var trial = {
type: 'html-keyboard-response'
stimulus: '+',
post_trial_gap: random_duration // if you use a named function for a dynamic parameter, then just use the function name (without parentheses after it)
}
```
### Storing changing variables in the data
The trial's `data` parameter can be also function, which is useful for when you want to save information to the data that can change during the experiment. For example, if you have a global variable called `current_difficulty` that tracks the difficulty level in an adaptive task, you can save the current value of this variable to the trial data like this:
```js
var current_difficulty; // value changes during the experiment
var trial = {
type: 'survey-text',
questions: [{prompt: "Please enter your response."}]
data: function() {
return {difficulty: current_difficulty};
}
}
```
It's also possible to use a function for any of the _individual properties_ in the trial's `data` object, for instance if you want to combine static and dynamic information in the data:
```js
var trial = {
type: 'survey-text',
questions: [{prompt: "Please enter your response."}]
data: {
difficulty: function() {
return current_difficulty; // the difficulty value changes during the experiment
},
task_part: 'recall', // this part of the data is always the same
block_number: 1
}
}
```
## Nested Parameters
Dyanmic parameters work the same way with nested parameters, which are parameters that contain one or more sets of other parameters. For instance, many survey-* plugins have a `questions` parameter that is a nested parameter: it is an array that contains the parameters for one or more questions on the page. To make the `questions` parameter dynamic, you can use a function that returns the array with all of the parameters for each question:
```js
var subject_id; // value is set during the experiment
var trial = {
type: 'survey-text',
questions: function(){
var questions_array = [
{prompt: "Hi "+subject_id+"! What's your favorite city?", required: true, name: 'fav_city'},
{prompt: "What is your favorite fruit?", required: true, name: 'fav_fruit'},
];
return questions_array;
}
}
```
You can also use a function for any of the _individual parameters_ inside of a nested parameter.
```js
var trial = {
type: 'survey-text',
questions: [
{
prompt: function() {
// this question prompt is dynamic - the text that is shown
// will change based on the participant's earlier response
var favorite_city = jsPsych.data.getLastTrialData().values()[0].response.fav_city;
var text = "Earlier you said your favorite city is "+favorite_city+". What do you like most about "+favorite_city+"?"
return text;
},
required: true,
rows: 40,
columns: 10
},
{ prompt: "What is your favorite fruit?", required: true, name: 'fav_fruit' }
]
}
```
## When dynamic parameters can't be used
Note that if the plugin *expects* the value of a given parameter to be a function, then this function *will not* be evaluated at the start of the trial. This is because some plugins allow the researcher to specify functions that should be called at some point during the trial. Some examples of this include the `stimulus` parameter in the canvas-* plugins, the `mistake_fn` parameter in the cloze plugin, and the `stim_function` parameter in the reconstruction plugin. If you want to check whether this is the case for a particular plugin and parameter, then the parameter's `type` in the `plugin.info` section of the plugin file. If the parameter type is `jsPsych.plugins.parameterType.FUNCTION`, then this parameter must be a function and it will not be executed before the trial starts.
Even though function evaluation doesn't work the same way with these parameters, the fact that the parameters are functions means that you can get the same dynamic functionality. These functions are typically evaluated at some point during the trial, so you still get updates to values within the function during the trial.

View File

@ -2,13 +2,14 @@
There are several options that can be set when calling `jsPsych.init()` to launch the experiment.
Options are specified in the object passed to `jsPsych.init`. For example, to specify a set of images to preload and the default inter-trial interval the object would contain:
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:
```js
jsPsych.init({
timeline: [...],
preload_images: ['img1.png', 'img2.png'],
default_iti: 500
default_iti: 250,
minimum_valid_rt: 100,
experiment_width: 800
});
```
@ -50,17 +51,17 @@ Exclusion criteria can be specified based on features of the user's web browser,
## Display a progress bar
An automatic or manually updated progress bar can be displayed at the top of the screen. 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 `jsPsych.init`. See the [progress bar page](progress-bar.md) for more details.
## Preload media elements
Images, audio files, and movies can be preloaded to reduce latency during the experiment. In many cases, this preloading is automatic. In certain situations, such as using a custom plugin, using [timeline variables](timeline.md#timeline-variables), or using [functions to determine which stimulus to show](trial.md#dynamic-parameters), it is necessary to provide jsPsych with a list of media elements to preload. The [media preloading](media-preloading.md) page describes this process in detail.
Images, audio files, and movies can be preloaded to reduce latency during the experiment. In many cases, this preloading is automatic. In certain situations, such as using a custom plugin, using [timeline variables](timeline.md#timeline-variables), or using [functions to determine which stimulus to show](dynamic-parameters.md), it is necessary to provide jsPsych with a list of media elements to preload. The [media preloading](media-preloading.md) page describes this process in detail.
## Choose the method for playing audio files
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 `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.
However, loading files through the WebAudio API may not work when running an experiment locally (i.e., not on a live web server). This is due to the [cross-origin security policy](https://security.stackexchange.com/a/190321) implemented by web browsers. One option is to [temporarily disable the security](https://stackoverflow.com/q/4819060/3726673) for testing purposes. Another is to use HTML5 Audio instead of the WebAudio API. This can be done by specifying the `use_webaudio` parameter in `jsPsych.init()`.
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
jsPsych.init({
@ -95,3 +96,58 @@ jsPsych.init({
});
```
## Specify a minimum valid response time
By default, jsPsych will treat any keyboard response time as valid. However, it's possible to specify a minimum valid response time (in ms) for key presses. Any key press 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.
```js
// ignore any keyboard responses that are less than 100 ms
jsPsych.init({
timeline: [...],
minimum_valid_rt: 100
});
```
## Choose whether you want keyboard choices/responses to be case-sensitive
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` parameter to `true` in `jsPsych.init`.
```js
// use case-sensitive key choices and responses,
// 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
jsPsych.init({
timeline: [...],
case_sensitive: true
});
```
Note that this setting only applies to key choices and responses that use jsPsych's keyboard response listener, such as in the *`-keyboard-response` plugins. This does NOT apply to responses that are made by typing into a text box, such as in the `survey-text` and `cloze` plugins.
## Override 'safe mode' when running experiments offline
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.
```js
jsPsych.init({
timeline: [...],
override_safe_mode: true
});
```
## 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.
```js
jsPsych.init({
timeline: [...],
extensions: [
{type: 'webgazer'}
]
});
```

View File

@ -0,0 +1,237 @@
# Eye Tracking
jsPsych supports eye tracking through the [WebGazer](https://webgazer.cs.brown.edu/) library. WebGazer uses computer vision techniques to identify features of the participant's eyes via a webcam and predicts gaze location. The system is calibrated by having the participant click on or look at known locations on the screen. These locations are linked to eye features. Gaze location is predicted using regression.
## Getting Started
First, [download WebGazer.js ](https://webgazer.cs.brown.edu/#download) and include it in your experiment file via a `<script>` tag. You'll also need to include jsPsych's [webgazer extension](/extensions/jspsych-ext-webgazer.md).
```html
<head>
<script src="jspsych/jspsych.js"></script>
<script src="webgazer.js"></script>
<script src="jspsych/extensions/jspsych-ext-webgazer.js"></script>
</head>
```
!!! tip
An example experiment using WebGazer is available in the **/examples** folder of the jsPsych release. See `webgazer.html`.
To use the WebGazer extension in an experiment, include it in the list of extensions passed to `jsPsych.init()`
```js
jsPsych.init({
timeline: [...],
extensions: [
{type: 'webgazer'}
]
})
```
To help the participant position their face correctly for eye tracking you can use the [jspsych-webgazer-init-camera plugin](/plugins/jspsych-webgazer-init-camera.ms). This will show the participant what the camera sees, including facial feature landmarks, and prevent the participant from continuing until their face is in good position for eye tracking.
```js
var init_camera_trial = {
type: 'webgazer-init-camera'
}
```
To calibrate WebGazer, you can use the [jspsych-webgazer-calibrate plugin](/plugins/jspsych-webgazer-calibrate.md). This plugin allows you to specify a set of points on the screen for calibration and to choose the method for calibrating -- either clicking on each point or simply fixating on each point. The location of calibration points is specified in percentages, e.g., `[25,50]` will result in a point that is 25% of the width of the screen from the left edge and 50% of the height of the screen from the top edge. Options for controlling other details of the calibration are explained in the [documentation for the plugin](/plugins/jspsych-webgazer-calibrate.md).
Note that instructions are not included in the calibration plugin, so you'll likely want to use a different plugin (e.g., `html-button-response`) to display instructions prior to running the calibration.
```js
var calibration_trial = {
type: 'webgazer-calibrate',
calibration_points: [[25,50], [50,50], [75,50], [50,25], [50,75]],
calibration_mode: 'click'
}
```
To measure the accuracy and precision of the calibration, you can use the [jspsych-webgazer-vaidate plugin](/plugins/jspsych-webgazer-validate.md). Like the calibration plugin, you can specify a list of points to perform validation on. Here you can specify the points as either percentages or in terms of the distance from the center of the screen in pixels. Which mode you use will probably depend on how you are defining your stimuli throughout the experiment. You can also specify the radius of tolerance around each point, and the plugin will calculate the percentage of measured gaze samples within that radius. This is a potentially useful heuristic for deciding whether or not to calibrate again. Options for controlling other details of the validation are explained in the [documentation for the plugin](/plugins/jspsych-webgazer-validate.md).
```js
var validation_trial = {
type: 'webgazer-validate',
validation_points: [[-200,200], [200,200],[-200,-200],[200,-200]],
validation_point_coordinates: 'center-offset-pixels',
roi_radius: 100
}
```
The validation procedure stores the raw gaze data for each validation point, the computed average offset from each validation point, the percentage of samples within the `roi_radius` for each validation point, and the number of samples collected per second.
```js
{
raw_gaze: [...],
percent_in_roi: [...],
average_offset: [...],
samples_per_sec: ...
}
```
We recommend performing calibration and validation periodically throughout your experiment.
To enable eye tracking for a trial in your experiment, you can simply add the WebGazer extension to the trial.
```js
var trial = {
type: 'html-keyboard-response',
stimulus: '<img id="scene" src="my-scene.png"></img>',
extensions: [
{
type: 'webgazer',
params: {
targets: ['#scene']
}
}
]
}
```
This will turn on WebGazer at the start of the trial.
The `params` property in the `extensions` declaration allows you to pass in a list of [CSS selector strings](https://www.w3schools.com/cssref/css_selectors.asp). The [bounding rectangle](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect) of the DOM element that matches each selector will be recorded in the data for that trial. This allows for easy alignment of the gaze data and objects on the screen.
```js
webgazer_targets : [
{selector: ..., top: ..., left: ..., right: ..., bottom:...},
{selector: ..., top: ..., left: ..., right: ..., bottom:...},
]
```
Gaze data will be added to the trial's data under the property `webgazer_data`. The gaze data is an array of objects. Each object has an `x`, a `y`, and a `t` property. The `x` and `y` properties specify the gaze location in pixels and `t` specifies the time in milliseconds since the start of the trial. Note that establishing the precision and accuracy of these measurements across the variety of web browsers and systems that your experiment participants might be using is quite difficult. For example, different browsers may cause small systematic shifts in the accuracy of `t` values.
```js
webgazer_data: [
{x: ..., y: ..., t: ...},
{x: ..., y: ..., t: ...},
{x: ..., y: ..., t: ...},
{x: ..., y: ..., t: ...}
]
```
## Tips for Improving Data Quality
These are some anecdotal observations about factors that improve data quality.
1. The quality of the camera feed is essential. Good lighting makes a big difference. You may want to encourage participants to perform any eye tracking experiments in a well-lit room.
2. Participants need to keep their head relatively still during and after calibration. The calibration is not robust to head movements.
3. WebGazer's click-based calibration can be used throughout the experiment. You can turn this on by calling `jsPsych.extensions.webgazer.startMouseCalibration()` at any point in the experiment. If you use a continue button to advance through the experiment and move the location of the continue button around you can be making small adjustments to the calibration throughout.
4. Computing the gaze predictions consumes more computational resources than most other things that jsPsych is typically used for. The sampling rate that WebGazer is able to achieve will depend on the computing power of the participant's device. You may want to ask the participant to close any non-essential software and browser windows prior to completing the experiment. You may also want to check that the sampling rate is sufficiently high as part of validation.
If you have tips based on your own experience please consider sharing them on our [discussion forum](https://github.com/jspsych/jsPsych/discussions) and we'll add to this list!
## Example
The code below shows a basic example of what it looks like when you put all of these things together in your experiment's HTML file.
```html
<html>
<head>
<script src="jspsych/jspsych.js"></script>
<script src="jspsych/plugins/jspsych-preload.js"></script>
<script src="jspsych/plugins/jspsych-image-keyboard-response.js"></script>
<script src="jspsych/plugins/jspsych-html-keyboard-response.js"></script>
<script src="jspsych/plugins/jspsych-webgazer-init-camera.js"></script>
<script src="jspsych/plugins/jspsych-webgazer-calibrate.js"></script>
<script src="jspsych/plugins/jspsych-webgazer-validation.js"></script>
<script src="js/webgazer.js"></script>
<script src="jspsych/extensions/jspsych-ext-webgazer.js"></script>
<link rel="stylesheet" href="jspsych/css/jspsych.css">
</head>
<body></body>
<script>
var preload = {
type: 'preload',
images: ['img/blue.png']
}
var init_camera = {
type: 'webgazer-init-camera'
}
var calibration = {
type: 'webgazer-calibrate'
}
var validation = {
type: 'webgazer-validate'
}
var start = {
type: 'html-keyboard-response',
stimulus: 'Press any key to start.'
}
var trial = {
type: 'image-keyboard-response',
stimulus: 'img/blue.png',
choices: jsPsych.NO_KEYS,
trial_duration: 1000,
extensions: [
{
type: 'webgazer',
params: {targets: ['#jspsych-image-keyboard-response-stimulus']}
}
]
}
jsPsych.init({
timeline: [init_camera, calibration, validation, start, trial],
preload_images: ['img/blue.png'],
extensions: [
{type: 'webgazer'}
]
})
</script>
</html>
```
Below is example data from the image-keyboard-response trial taken from the experiment above. In addition to the standard data that is collected for this plugin, you can see the additional `webgazer_data` and `webgazer_targets` arrays. The `webgazer_data` shows 21 gaze location estimates during the 1-second image presentation. The `webgazer_targets` array shows that there was one target, the image-keyboard-response stimulus, and tells you the x- and y-coordinate boundaries for the target (image) rectangle. By comparing each of the x/y locations from the `webgazer_data` locations array with the target boundaries in `webgazer_targets`, you can determine if/when the estimated gaze location was inside the target area.
```js
{
"rt": null,
"stimulus": "img/blue.png",
"response": null,
"trial_type": "image-keyboard-response",
"trial_index": 4,
"time_elapsed": 30701,
"internal_node_id": "0.0-4.0",
"webgazer_data": [
{ "x": 1065, "y": 437, "t": 39},
{ "x": 943, "y": 377, "t": 79},
{ "x": 835, "y": 332, "t": 110},
{ "x": 731, "y": 299, "t": 146},
{ "x": 660, "y": 271, "t": 189},
{ "x": 606, "y": 251, "t": 238},
{ "x": 582, "y": 213, "t": 288},
{ "x": 551, "y": 200, "t": 335},
{ "x": 538, "y": 183, "t": 394},
{ "x": 514, "y": 177, "t": 436},
{ "x": 500, "y": 171, "t": 493},
{ "x": 525, "y": 178, "t": 542},
{ "x": 537, "y": 182, "t": 592},
{ "x": 543, "y": 178, "t": 633},
{ "x": 547, "y": 177, "t": 691},
{ "x": 558, "y": 174, "t": 739},
{ "x": 574, "y": 183, "t": 789},
{ "x": 577, "y": 197, "t": 838},
{ "x": 584, "y": 214, "t": 889},
{ "x": 603, "y": 218, "t": 937},
{ "x": 606, "y": 221, "t": 987}
],
"webgazer_targets": [
{
"selector": "#jspsych-image-keyboard-response-stimulus",
"top": 135.33334350585938,
"bottom": 435.3333435058594,
"left": 490,
"right": 790
}
]
}
```

View File

@ -1,60 +1,69 @@
# Media Preloading
If an experiment uses image, audio, or video files as stimuli, it is a good idea to preload the files before running the experiment. Preloading files means that the subject's browser will download all of the files and store them in local memory on the subject's computer. This is important because loading a file is much faster if it is already in memory on the subject's computer. Without preloading, there will be noticeable delays in the display of media, which will affect any timing measurements (such as how long an image is displayed, or a subject's response time since first viewing an image). For particularly large files, like video, preloading content avoids lengthy pauses in the middle of the experiment that can be disruptive to the flow of the experiment.
If an experiment uses image, audio, or video files as stimuli, it is a good idea to preload the files before running the experiment. You can preload files at any point in your experiment using the [jsPsych `preload` plugin](../plugins/jspsych-preload.md). Preloading files means that the subject's browser will download the files and store them in local memory on the subject's computer. This is important because displaying or playing a media file is much faster if it is already in memory on the subject's computer. Without preloading, there will be noticeable delays in the display of media, which will affect any timing measurements (such as how long an image is displayed, or a subject's response time since first viewing an image). For particularly large files, like video, preloading content avoids lengthy pauses in the middle of the experiment that can be disruptive to the flow of the experiment.
!!! warning
Note that video preloading will not work when you run your experiment offline (e.g., by double-clicking on the HTML file), but it will work once your experiment is running online (hosted on a server). The [Cross-origin requests (CORS) and safe mode](running-experiments.md#cross-origin-requests-cors-and-safe-mode) section on the Running Experiments page contains more information about this.
## Automatic Preloading
jsPsych will automatically preload audio, video, and image files that are used as parameters for the standard set of plugins.
jsPsych can automatically preload audio, video, and image files that are used as parameters for the standard set of plugins, based on the timeline that is passed to `jsPsych.init`. You must initiate this preloading using a `preload` trial. You should add this `preload` trial into your timeline when you want the preloading to occur, and set the `auto_preload` parameter to `true`.
```javascript
// the image file img/file1.png is
// automatically preloaded before the experiment begins
var trial = {
// the "auto_preload: true" setting tells the plugin to automatically find stimuli to preload based
// the main experiment timeline (used in jsPsych.init)
var preload = {
type: 'preload',
auto_preload: true
}
// this image file can be automatically preloaded
var image_trial = {
type: 'image-keyboard-response',
stimulus: 'img/file1.png'
}
// the sound file is also preloaded automatically
// the sound file can be automatically preloaded
var sound_trial = {
type: 'audio-keyboard-response',
stimulus: 'audio/hello.mp3'
}
// the video file is preloaded automatically
// the video file can be automatically preloaded (as long as the experiment is running on a server)
var video_trial = {
type: 'video',
sources: ['video/sample_video.mp4']
stimulus: ['video/sample_video.mp4']
}
jsPsych.init({
timeline: [trial]
timeline: [preload, image_trial, sound_trial, video_trial]
});
```
## Manual preloading
If you are using media files in your experiment but they are not being passed directly as parameters to the trials (e.g., because you are using functions as parameters that return the audio, video, or images, or you are using timeline variables), then you can manually specify the files to preload.
You can specify an array of image files (`preload_images`) and an array of audio files (`preload_audio`) for preloading in the `jsPsych.init()` method. These files will load before the experiment starts.
If you are using media files in your experiment but they are not being passed directly as parameters to the trials (e.g., because you are using functions as parameters that return the media files, you are using timeline variables, or you are embedding the media files in an HTML string), then these files will not be detected when you use the `auto_preload` option, so you must manually specify them. The `preload` plugin allows you to add these files using the `images`, `audio` and `video` parameters.
```javascript
// this trial will not preload the images, because the image file is being used
// in an HTML string
var trial = {
// this image file cannot be automatically preloaded because it is embedded in an HTML string
var image_trial = {
type: 'html-keyboard-response',
stimulus: '<img src="img/file1.png"></img>',
}
var audio_trial = {
// this audio file cannot be automatically preloaded because it is returned from a function
var sound_trial = {
type: 'audio-keyboard-response',
stimulus: function() { return 'audio/foo.mp3' }
stimulus: function() { return 'audio/sound1.mp3' }
}
var video_timline = {
// these video files cannot be automatically preloaded because they are passed into a trial
// using the jsPsych.timelineVariable function
var video_trials = {
timeline: [
{
type: 'video',
sources: jsPsych.timelineVariable('video')
stimulus: jsPsych.timelineVariable('video')
}
],
timeline_variables: [
@ -63,27 +72,290 @@ var video_timline = {
]
}
// an array of paths to images that need to be loaded
// to manually preload media files, create an array of file paths for each media type
var images = ['img/file1.png'];
var audio = ['audio/foo.mp3'];
var audio = ['audio/sound1.mp3'];
var video = ['video/1.mp4', 'video/2.mp4'];
// these array can be passed into the preload plugin using the images, audio and video parameters
var preload = {
type: 'preload',
images: images,
audio: audio,
video: video
}
jsPsych.init({
timeline: [trial],
preload_audio: audio,
preload_images: images,
preload_video: video
timeline: [preload, image_trial, sound_trial, video_trials],
});
```
## Combining automatic and manual preloading
It's possible to combine automatic and manual preloading. For instance, you may want to automatically preload all of the media files based on your experiment timeline, while also manually preloading any files that can't be automatically preloaded. Any duplicate file names across all preloading methods will be removed before preloading starts, so including the same file names in multiple `preload` parameters will not affect the preloading duration.
```javascript
// this file can be preloaded automatically
var image_trial = {
type: 'image-keyboard-response',
stimulus: 'img/file1.png'
}
// this file can be preloaded automatically
var sound_trial = {
type: 'audio-keyboard-response',
stimulus: 'audio/hello.mp3'
}
// these files must be preloaded manually
var video_trials = {
timeline: [
{
type: 'video',
stimulus: jsPsych.timelineVariable('video')
}
],
timeline_variables: [
{video: ['video/1.mp4']},
{video: ['video/2.mp4']}
]
}
var video = ['video/1.mp4', 'video/2.mp4'];
var preload = {
type: 'preload',
auto_preload: true, // automatically preload the image and audio files
video: video // manually preload the videos used with timeline variables
}
jsPsych.init({
timeline: [preload, image_trial, sound_trial, video_trials],
});
```
## Preloading in batches
Some experiments use many and/or large media files. This can cause problems when participants have slow and/or unreliable internet connections, because it increases the chances of loading errors during preloading. This can also cause problems with file caching, i.e. ensuring that the preloaded files remain in the browser's memory, because loading all stimuli at once may exceed the browser's cache limits. One option for mitigating these problems is to load the media files in smaller batches throughout the experiment. Files should be preloaded as close as possible to when they will be needed. For instance, if you have several blocks of trials, then right before each block, you can preload the stimuli that are needed for that block.
Here is an example with trials where the stimuli files can be preloaded automatically. In this case, the `trials` parameter is used to tell the `preload` plugin to preload the stimuli from a specific part of the timeline.
```javascript
// these image files in these trial blocks can be automatically preloaded
var block_1 = {
timeline: [
{
type: 'image-keyboard-response',
stimulus: 'img/file1.png'
},
{
type: 'image-keyboard-response',
stimulus: 'img/file2.png'
}
]
}
var block_2 = {
timeline: [
{
type: 'image-keyboard-response',
stimulus: 'img/file3.png'
},
{
type: 'image-keyboard-response',
stimulus: 'img/file4.png'
}
]
}
var preload_1 = {
type: 'preload',
trials: block_1 // automatically preload just the images from block_1 trials
}
var preload_2 = {
type: 'preload',
trials: block_2 // automatically preload just the images from block_2 trials
}
jsPsych.init({
// add each preload trial onto the main timeline before the appropriate trial block
timeline: [preload_1, block_1, preload_2, block_2],
});
```
Below is an example with trials where the stimuli files cannot be preloaded automatically, because the stimuli files are passed to the trials via `jsPsych.timelineVariable`. In this case, we create separate arrays for each batch of files, and then pass those arrays to the each preload trial.
```javascript
// these trial blocks cannot be automatically preloaded,
// because the media files are passed to the trial parameters with timeline variables
var block_1 = {
timeline: [...],
timeline_variables: [
{stim: 'file1.png'},
{stim: 'file1.png'}
]
}
var block_2 = {
timeline: [...],
timeline_variables: [
{stim: 'file3.png'},
{stim: 'file4.png'}
]
}
var images_block_1 = ['file1.png', 'file2.png'];
var images_block_2 = ['file3.png', 'file4.png'];
// preload trial for preloading the block 1 stimuli
var preload_1 = {
type: 'preload',
images: images_block_1
}
// preload trial for preloading the block 2 stimuli
var preload_2 = {
type: 'preload',
images: images_block_2
}
jsPsych.init({
// add each preload trial to the main timeline before the appropriate trial block
timeline: [preload_1, block_1, preload_2, block_2],
});
```
## Preloading progress bar
By default, jsPsych will display a small progress bar while files are being preloaded. This progress bar represents all files that are being automatically preloaded or preloaded from the `preload_audio`, `preload_video`, and `preload_images` arrays. You may wish to turn this off if you are only loading a small number of files, as it will disappear so quickly that the participant may be confused about what it was. You can control whether the preloading progress bar appears by setting the `show_preload_progress_bar` parameter in `jsPsych.init()`
By default, the `preload` plugin will display a progress bar while files are being preloaded. This progress bar represents all files that are being preloaded during the trial, regardless of whether the file is being preloaded automatically via the `auto_preload` or `trials` parameters, or manually via the `audio`, `images`, and `video` parameters. You may wish to turn the preload progress bar off if you are only loading a small number of files, as it will appear and disappear so quickly that the participant may be confused about what it was. You can control whether the preloading progress bar appears by setting the `show_progress_bar` parameter in the `preload` trial.
```javascript
jsPsych.init({
timeline: timeline,
show_preload_progress_bar: false // hide preload progress bar
});
var preload_trial = {
type: 'preload',
auto_preload: true
show_progress_bar: false // hide progress bar
}
```
## Loading time limits
It's usually a good idea to set a time limit for file loading, to ensure that participants aren't waiting for an unreasonable amount of time. Time limits can be specified in milliseconds using the `max_load_time` parameter. If you set a loading time limit and all files haven't finished loading before this time, then the `preload` trial will either stop an error (if `continue_after_error` is false, the default) or the trial will end and the experiment will continue (if `continue_after_error` is `true`). If `max_load_time` is `null` (the default), then there is no time limit.
```javascript
var preload_trial = {
type: 'preload',
auto_preload: true
max_load_time: 60000 // 1 minute
}
```
## Loading and error messages
It's possible to specify custom messages to be shown on the page while the media files are loading, and in case of one or more file loading errors. The `message` parameter allows you to customize the loading message using an HML-formatted string. If `show_progress_bar` is `true`, then this message will be shown above the progress bar.
```javascript
var preload_trial = {
type: 'preload',
auto_preload: true
message: 'Please wait while the experiment loads. This may take a few minutes.',
}
```
A preloading error will occur when either (a) one or more files produces a loading error, and/or (b) all files have not finished loading before the `max_load_time` duration. The `error_message` parameter allows you to customize the messsage that's shown on the page in these cases. This message will only be shown if `continue_after_error` is `false` (the default).
```javascript
var preload_trial = {
type: 'preload',
auto_preload: true,
error_message: 'The experiment failed to load. Please contact the researcher.'
}
```
In addition to the `error_message` parameter, it's also possible to show more detailed error messages on the page about any files that failed to load. You can control this with the `show_detailed_errors` parameter. Detailed error messages will appear below the general error message. This only applies if `continue_after_error` is `false` (the default).
Detailed error messages can be useful when testing and debugging your experiment. If `show_detailed_errors` is `true`, then if one or more loading errors occurs before the `max_load_time` is reached, then the error page will also contian a list of the file(s) that produced an error, along with error information (if there is any). Note that this may not be a complete list, because it will only report any errors that occurred before the `max_load_time` was reached. If there are no file loading errors but preloading hasn't finished before the `max_load_time`, then detailed error message will just tell you that loading timed out.
```javascript
var preload_trial = {
type: 'preload',
auto_preload: true
show_detailed_errors: true // show details of any file loading errors and/or loading time out
}
```
## Options for handling errors
If `continue_after_error` is `true`, then the experiment _will not stop_ if one or more files fails to load. Instead, the trial will end and the experiment will continue. However, the preload trial data will contain a property called `success`, which is whether or not all files were loaded successfully, `timeout`, which is whether or not the files loaded successfully before the `max_load_time`. The preload trial data will also contain lists of any `image`, `audio`, and `video` files that failed to load. This gives you the option to continue the experiment after preloading fails and use the preload trial data decide what to do next. For instance, you may decide to skip the trials that use the stimuli files that failed to load, or try loading the failed files again. Another option is to simply end the experiment when preloading fails, but send the data back to your server so that you have more information about the loading failure.
```javascript
var preload_trial = {
type: 'preload',
auto_preload: true
message: 'Please wait while the experiment loads...',
continue_after_error: true // don't stop the experiment if there are file loading errors or if loading times out
}
var save_data = {
type: 'call-function',
async: true,
func: function(done){
var data = jsPsych.data.get().json();
save_data(data, function() {done()})
}
}
var fail_message = {
type: 'html-keyboard-response',
stimulus: 'The experiment failed to load. Please contact the researcher.',
choices: jsPsych.NO_KEYS,
trial_duration: null // the experiment will stop here, since there are no valid key choices or trial duration
}
var if_loading_fails = {
timeline: [save_data, fail_message],
conditional_function: function() {
if (jsPsych.data.getLastTrialData()[0].values().success) {
// preloading was successful, so skip this conditional timeline
// and move on with the experiment
return false;
} else {
// preloading failed, so run this conditional timeline:
// save the data to the server and show the fail message
return true;
}
}
}
// ... rest of experiment
jsPsych.init({
timeline: [preload_trial, if_loading_fails, ... ]
})
```
The `preload` plugin's `on_success` and `on_error` callback functions provide another way of tracking preloading progress and handling file loading errors. These functions are called after any file either loads successfully or produces an error, respectively. These functions receive a single argument, which is the path of the file (string) that loaded or produced an error.
```javascript
var file_load_count = 0;
var file_error_count = 0;
var preload_trial = {
type: 'preload',
auto_preload: true,
on_error: function(file) {
file_error_count++;
console.log('Error: ',file);
},
on_success: function(file) {
file_load_count++;
console.log('Loaded: ',file);
}
};
```
Note that there's no guarantee that any/all files will trigger one of these two callback functions, because they are cancelled after the `preload` trial ends. For instance, if a file takes longer to load then the `max_load_time`, then the `preload` trial will end due to timing out, and the `on_success` and `on_error` callbacks for any in-progress files will be cancelled.

259
docs/overview/plugins.md Normal file
View File

@ -0,0 +1,259 @@
# Plugins
In jsPsych, plugins define the kinds of trials or events that should occur during the experiment. Some plugins define very general events, like displaying a set of instructions pages, displaying an image and recording a keyboard response, or playing a sound file and recording a button response. Other plugins are more specific, like those that display particular kinds of stimuli (e.g. Random-Dot Kinematogram, visual search circle), or run a specific version of particular kind of task (e.g. the Implicit Association Test). Creating an experiment with jsPsych involves figuring out which plugins are needed to create the tasks you want your participants to perform.
Plugins provide a structure for a particular trial or task, but often allow for significant customization and flexibility. For example, the `image-keyboard-response` plugin defines a simple structure for showing an image and collecting a keyboard response. You can specify the what the stimulus is, what keys the subject is allowed to press, and how long the stimulus should be on the screen, how long the subject has to respond, and so on. Many of these options have reasonable default values; even though the image plugin has many different parameters, you only *need* to specify the image stimulus in order to use it. Each plugin has its own documentation page, which describes what the plugin does, what options are available, and what kind of data it collects.
## Using a plugin
To use a plugin, you'll need to load the plugin's JavaScript file in your experiment's HTML page. All jsPsych experiments also need to load the "jsPsych.js" file.
```html
<head>
<script src="jsPsych/jspsych.js" type="text/javascript"></script>
<script src="jsPsych/plugins/jspsych-image-keyboard-response.js" type="text/javascript"></script>
</head>
```
Once a plugin is loaded, you can use JavaScript to define a trial that uses that plugin. All jsPsych trials have a `type`, which tells jsPsych what plugin to use to run the trial. The trial's `type` is the plugin name, which usually the same as the plugin file name, but with the "jspsych-" prefix removed.
The following JavaScript code defines a trial using the `image-keyboard-response` plugin to display an image file. This trial uses the default values for valid keys, stimulus duration, trial duration, and other parameters.
```javascript
var image_trial = {
type: 'image-keyboard-response',
stimulus: 'images/happy_face.jpg'
}
```
You can override any default parameter values by adding them into your trial object. Here's an exampe of overriding the default values for `trial_duration` and `post_trial_gap`:
```javascript
var image_trial = {
type: 'image-keyboard-response',
stimulus: 'images/happy_face.jpg',
trial_duration: 3000,
post_trial_gap: 2000
}
```
## Parameters available in all plugins
Each plugin specifies its own set of parameters. Check the documentation for a plugin to see what parameters are available and what they do.
There is also a set of parameters that can be specified for any plugin:
| Parameter | Type | Default Value | Description |
| -------------- | -------- | ----------------------- | ---------------------------------------- |
| data | object | *undefined* | An object containing additional data to store for the trial. See [the Data page](../overview/data.md) for more details. |
| post_trial_gap | numeric | null | Sets the time, in milliseconds, between the current trial and the next trial. If null, there will be no gap. |
| on_start | function | `function(){ return; }` | A callback function to execute when the trial begins, before any loading has occurred. See [the Event-Related Callbacks page](../overview/callbacks.md) for more details. |
| on_finish | function | `function(){ return; }` | A callback function to execute when the trial finishes, and before the next trial begins. See [the Event-Related Callbacks page](../overview/callbacks.md) for more details. |
| on_load | function | `function(){ return; }` | A callback function to execute when the trial has loaded, which typically happens after the initial display of the plugin has loaded. See [the Event-Related Callbacks page](../overview/callbacks.md) for more details. |
| css_classes | string | null | A list of CSS classes to add to the jsPsych display element for the duration of this trial. This allows you to create custom formatting rules (CSS classes) that are only applied to specific trials. For more information and examples, see the [Controlling Visual Appearance page](../overview/style.md) and the "css-classes-parameter.html" file in the jsPsych examples folder. |
### The data parameter
The `data` parameter allows you to add additional properties to the trial data. This can be useful for storing properties of the trial that are not directly apparent from the values that the plugin records. The `data` parameter value should be an object that contains key-value pairs.
A simple example is the [Flanker Task](https://en.wikipedia.org/wiki/Eriksen_flanker_task). In this experiment, participants respond to the direction of a central arrow by pressing a key to the left for a left-pointing arrow (<) and a key to the right for a right-pointing arrow (>). The arrow appears in the center of *flankers*, or arrows that the participant should ignore. Those flankers can be congruent (>>>>>) or incongruent (<<><<).
A trial for the Flanker Task written with jsPsych might look like this:
```javascript
var trial = {
type: 'html-keyboard-response',
stimulus: '<<<<<',
choices: ['f','j'],
data: {
stimulus_type: 'congruent',
target_direction: 'left'
}
}
```
Note the use of the data parameter to add a property `stimulus_type` with the value `congruent` and a property `target_direction` with the value `left`. Having these properties recorded directly in the data simplifies data analysis, making it easy to aggregate data by `stimulus_type` and/or `target_direction`.
### 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 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`.
```javascript
var trial = {
type: 'html-keyboard-response',
stimulus: 'There will be a 1.5 second blank screen after this trial.',
post_trial_gap: 1500
}
```
### The on_start parameter
Immediately before a trial runs, there is an opportunity to run an arbitrary function through the `on_start` event handler. This event handler is passed a single argument containing an *editable* copy of the trial parameters. This function can therefore be used to alter the trial based on the state of the experiment, among other uses.
```javascript
// when this trial runs, the on_start function will change the trial's stimulus and data parameters,
// so the trial will display an incongruent Flanker stimulus with a right-facing central arrow
var trial = {
type: 'html-keyboard-response',
stimulus: '<<<<<',
choices: ['f','j'],
data: {
stimulus_type: 'congruent',
target_direction: 'left'
},
on_start: function(trial){
trial.stimulus = '<<><<';
trial.data.stimulus_type = 'incongruent';
trial.data.target_direction = 'right';
}
}
```
### The on_finish parameter
After a trial is completed, there is an opportunity to run an arbitrary function through the `on_finish` event handler. This function is passed a single argument containing an *editable* copy of the data recorded for that trial. This function can therefore be used to update the state of the experiment based on the data collected, or modify the data collected.
The `on_finish` function can be useful to calculate new data properties that were unknowable at the start of the trial. For example, with the Flanker Task example above, the `on_finish` function could check the response and use to this information to add a new property to the data called `correct`, which is either `true` or `false`.
```javascript
// in addition to all of the standard data collected for this trial,
// this on_finish function adds a property called 'correct'
// which is either 'true' or 'false'
// depending on the response that was made
var trial = {
type: 'html-keyboard-response',
stimulus: '<<<<<',
choices: ['f','j'],
data: {
stimulus_type: 'congruent',
target_direction: 'left',
correct_response: 'f'
},
on_finish: function(data){
if(data.response == data.correct_response){
data.correct = true;
} else {
data.correct = false;
}
}
}
```
### The on_load parameter
The `on_load` callback function will trigger once the trial has completed loading. For most plugins, this will occur once the display has been initially updated but before any user interactions or timed events (e.g., animations) have occurred. This can be useful for changing various aspects of the page elements and their properties that would otherwise require modifying the plugin file.
```javascript
var trial = {
type: 'image-keyboard-response',
stimulus: 'imgA.png',
on_load: function() {
// this will change the src attribute of the image after 500ms
setTimeout(function(){
document.querySelector('img').src = 'imgB.png'
}, 500);
}
};
```
## Data collected by all plugins
Each plugin defines what data is collected on the trial. The documentation for each plugin specifies what information will be stored in the trial data.
In addition to the data collected by a plugin, there is a default set of data that is collected on every trial.
| Name | Type | Value |
| ---------------- | ------- | ---------------------------------------- |
| trial_type | string | The name of the plugin used to run the trial. |
| trial_index | numeric | The index of the current trial across the whole experiment. |
| time_elapsed | numeric | The number of milliseconds between the start of the experiment and when the trial ended. |
| internal_node_id | string | A string identifier for the current TimelineNode. |
## Creating a new plugin
You can add new kinds of tasks to jsPsych by creating new plugins, or modifying existing plugins. A task can be virtually any kind of activity. If it can be implemented in JavaScript, then it almost certainly can be turned into a jsPsych plugin.
### What's in a plugin file?
Plugin files follow a specific template. Adherence to the template is what allows jsPsych to run a plugin without knowing anything about what the plugin is doing. What makes plugins so flexible is that the template imposes very few requirements on the code. Here's what an empty plugin template looks like:
```js
jsPsych.plugins['plugin-name'] = (function(){
var plugin = {};
plugin.info = {
name: 'plugin-name',
parameters: {
}
}
plugin.trial = function(display_element, trial){
jsPsych.finishTrial();
}
return plugin;
})();
```
This plugin will work! It defines a plugin called 'plugin-name', and it does absolutely nothing. However, it won't break the experiment, and jsPsych will understand that this is a valid plugin.
Let's examine it in more detail.
The overall structure of the plugin is defined using a module JavaScript design pattern. This pattern uses a technique called an anonymous closure. This is why the first line has `(function(){` and the last line is `})();`. The details aren't important, but if you want to learn more about it, [this is a nice overview](http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html). The reason this pattern is useful is because it allows for persistent state and private scope. In other words, the plugin is isolated and can't be altered by other plugins.
The module, created by the `(function(){` `})();` expressions, contains an object called `plugin`. The `plugin` object has two properties: `info` and `trial`. The `plugin` object is returned at the end of the module, which is what assigns the defined properties of `plugin` to `jsPsych['plugin-name']`.
### plugin.info
The plugin's `info` property is an object that contains all of the available parameters for the plugin. Each parameter name is a property, and the value is an object that includes a description of the parameter, the value's type (string, integer, etc.), and the default value. See some of the plugin files in the jsPsych plugins folder for examples.
jsPsych allows most [plugin parameters to be dynamic](dynamic-parameters.md), which means that the parameter value can be a function that will be evaluated right before the trial starts. However, if you want your plugin to have a parameter that is a function that _shouldn't_ be evaluated before the trial starts, then you should make sure that the parameter type is `'FUNCTION'`. This tells jsPsych not to evaluate the function as it normally does for dynamic parameters. See the `canvas-*` plugins for examples.
### plugin.trial
The plugin's `trial` property is a function that runs a single trial. There are two parameters that are passed into the trial method. The first, `display_element`, is the DOM element where jsPsych content is being rendered. This parameter will be an `HTMLElement`. Generally, you don't need to worry about this parameter being in the correct format, and can assume that it is an `HMTLElement` and use methods of that class. The second, `trial`, is an object containing all of the parameters specified in the corresponding TimelineNode. If you have specified all of your parameters in `plugin.info`, along with default values for each one, then the `trial` object will contain the default values for any parameters that were not specified in the trial's definition.
The only requirement for the `trial` method is that it calls `jsPsych.finishTrial()` when it is done. This is how jsPsych knows to advance to the next trial in the experiment (or end the experiment if it is the last trial). The plugin can do whatever it needs to do before that point.
Of course, there are other things that you will probably want the plugin to do inside the `plugin.trial` function, besides just end. Here are some examples:
### Changing the content of the display
There are a few ways to change the content of the display. The `display_element` parameter of the trial method contains the DOM element for displaying content, so you can use various JavaScript methods for interaction with the display element. A common one is to change the `innerHTML`.
```javascript
var html_content = '<p>This is the first paragraph</p>';
html_content += '<p>This is the second paragraph</p>';
display_element.innerHTML = html_content;
```
jsPsych doesn't clear the display before or after each trial, so it is often appropriate to use `innerHTML` to clear the display at the end of a trial:
```javascript
// clear the display
display_element.innerHTML = '';
```
### Writing data
Plugins exist to collect data, so saving data is obviously a crucial thing to do. You can pass an object of data as the parameter to `jsPsych.finishTrial()`:
```javascript
var data = {
correct: true,
rt: 350
}
jsPsych.finishTrial(data);
```
The data recorded will be that `correct` is `true` and that `rt` is `350`. Additional data for the trial will also be collected automatically by the jsPsych library.
### The plugin template
An empty plugin template is included in the `plugins/template` folder.

View File

@ -29,7 +29,7 @@ var trial = {
}
```
You can also get the current value of the progress bar with `jsPsych.getProgressBarCompleted()`
You can also get the current value of the progress bar with `jsPsych.getProgressBarCompleted()`.
```js
var proportion_complete = jsPsych.getProgressBarCompleted();
@ -44,3 +44,67 @@ jsPsych.init({
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:
```js
var n_trials = 5;
var start = {
type: 'html-keyboard-response',
stimulus: 'Press any key to start!',
on_start: function() {
// set progress bar to 0 at the start of experiment
jsPsych.setProgressBar(0);
}
};
var trial = {
type: 'html-keyboard-response',
stimulus: 'This is a trial!',
on_finish: function() {
// at the end of each trial, update the progress bar
// based on the current value and the proportion to update for each trial
var curr_progress_bar_value = jsPsych.getProgressBarCompleted();
jsPsych.setProgressBar(curr_progress_bar_value + (1/n_trials));
}
};
var trials = {
timeline: [trial],
repetitions: n_trials
};
var done = {
type: 'html-keyboard-response',
stimulus: 'Done!'
};
jsPsych.init({
timeline: [start, trials, done],
show_progress_bar: true,
auto_update_progress_bar: false
});
```
## 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`.
```js
// support for different spoken languages
jsPsych.init({
timeline: [...],
show_progress_bar: true,
message_progress_bar: 'Porcentaje completo'
});
```
```js
// no message
jsPsych.init({
timeline: [...],
show_progress_bar: true,
message_progress_bar: ''
});
```

78
docs/overview/prolific.md Normal file
View File

@ -0,0 +1,78 @@
# Intergrating with Prolific
[Prolific](https://www.prolific.co/?ref=5JCXZPVU) is a participant recruitment service aimed at research. Integrating a jsPsych experiment with Prolific requires capturing the participant's ID and sending the participant to a completion URL at the end of the experiment.
## Capturing the Participant ID, Study ID, and Session ID
When creating a study on Prolific you must provide the URL to your study. You can host your jsPsych experiment however you'd like to integrate with Prolific. Some options are discussed in the [hosting experiments section of the documentation](). Once you've got a URL to your experiment, you can enter that in the *study link* section of Prolific. Then, click the option to record Prolific IDs via URL parameters.
![Prolific screenshot](/img/prolific-study-link.png)
This will append information about the participant's prolific ID (`PROLIFIC_PID`), the study's ID (`STUDY_ID`), and the session ID (`SESSION_ID`) to the URL that participants use to access your experiment.
We can capture these variables with jsPsych, and add them to jsPsych's data. This can be done anywhere in your code. This code does not need to run as part of your experiment timeline.
```html
<script>
// capture info from Prolific
var subject_id = jsPsych.data.getURLVariable('PROLIFIC_PID');
var study_id = jsPsych.data.getURLVariable('STUDY_ID');
var session_id = jsPsych.data.getURLVariable('SESSION_ID');
jsPsych.data.addProperties({
subject_id: subject_id,
study_id: study_id,
session_id: session_id
});
// create the rest of the experiment
var timeline = [...]
jsPsych.init({
timeline: timeline
})
</script>
```
## Completing the Experiment
When the experiment is complete, Prolific requires that you send the participant to a specific URL that marks the session as complete on Prolific's server. The link is provided to you by Prolific in the *study completion* section of the setup.
![Prolific Study Completion Screenshot](/img/prolific-study-completion.png)
You can accomplish this in a couple different ways.
!!! warning
It's important that you've saved all the data from your experiment before the participant returns to Prolific. Make sure that any server communication has completed prior to redirecting the participant. One way to do this is by using the async features of the `call-function` plugin ([example](/plugins/jspsych-call-function/#async-function-call)).
### Participant clicks a link
One option is to create a trial that contains a link that the participant clicks to end the experiment and return to Prolific. For example, the `html-keyboard-response` plugin can be used to display text that includes a link. This could go on a debriefing page.
Here's an example trial that could be used. Note that `choices` is set to `jsPsych.NO_KEYS`, which will prevent the participant from continuing past this point in the experiment.
```js
var final_trial = {
type: 'html-keyboard-response',
stimulus: `<p>You've finished the last task. Thanks for participating!</p>
<p><a href="https://app.prolific.co/submissions/complete?cc=XXXXXXX">Click here to return to Prolific and complete the study</a>.</p>`,
choices: jsPsych.NO_KEYS
}
```
### Automatically redirect
A second option is to automatically redirect the participant to the completion URL when the experiment is finished. You could do this in a number of places in the jsPsych timeline.
Here's an example using the `on_finish` event for the entire experiment.
```js
jsPsych.init({
timeline: [...],
on_finish: function(){
window.location = "https://app.prolific.co/submissions/complete?cc=XXXXXXX"
}
});
```

View File

@ -0,0 +1,95 @@
# Running Experiments
You can run your jsPsych experiment:
**Offline**, by opening the HTML file directly in the browser using the `file://` protocol.
**Online**, by hosting the files on a web server using the `http://` or `https://` protocol.
The way that you run your experiment will have consequences for certain aspects about how the experiment works, and what your experiment will be able to do. This page explains what you need to know about both of these options.
## Offline
You can run your jsPsych experiment offline by opening the HTML file directly in a web browser, for instance by double-clicking on it. This uses the `file://` protocol. It's usually the fastest and easiest way to run through an experiment, and is very useful while writing and testing the code.
At some point you will need to move your experiment files onto a server and send the data to a database, since this is how you will ultimately collect the data (unless you're planning to collect data on your local computer). There are some important differences between the way the experiment runs offline compared to online via a web server.
Note that, unless noted, here we're using the word "server" to mean either a _local_ server (which runs on your computer and only makes the experiment files available from within that computer, and is often used during development), or a _remote_ server (which does not run on your computer and does share your experiment files over the internet).
### Cross-origin requests (CORS) and safe mode
Web browsers have a security policy called [cross-origin resource sharing (CORS)](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing) that determines whether the webpage can request files that come from a different origin (i.e. protocol, host/domain, and port). This isn't a problem when your study runs _online_, because in that case your experiment files all have the same origin. However, when you run your experiment _offline_, the CORS policy blocks some jsPsych features that require [loading local files](https://security.stackexchange.com/questions/190266/why-chrome-blocks-ajax-locally/190321#190321). If your experiment uses these features, then [CORS errors](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors) will prevent the experiment from running.
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`.
* **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`](../core_library/jspsych-core.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.
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.
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.
### Media loading
While running your experiment offline, any media files are likely to load very quickly because they are stored on your own computer's disk. Therefore you may not notice problems with file loading delays while running your experiment locally (either offline or on a _local_ server) because the files will load fast enough that they never cause disruption. However, when your experiment is hosted on a _remote_ server, the files will need to be transferred over the internet, which means they will take longer to load - in some cases much longer. Loading delays are most noticeable with media files: images, audio, and video. As explained on the [Media Preloading](media-preloading.md) page, loading delays during your experiment can cause problems for stimulus display and response times.
It is important to test your experiment to ensure that any media files are preloading successfully and not being requested again during the experiment. You can use the Network tab in your browser's developer tools to see when files are loaded and to simulate a slow internet connection (see [here](https://developers.google.com/web/tools/chrome-devtools/network) for Chrome Network tab documentation). If you are preloading many and/or large files, such as videos, you may want to increase the `max_load_time` parameter in [`the preload plugin`](../plugins/jspsych-preload.md) so that participants with slow/unreliable internet connections will be able to take part in your experiment.
### Permanent data storage
As explained in the [Data Storage, Aggregation, and Manipulation](data.md#data-in-jspsych-permanent-and-non-permanent-data) page, jsPsych stores information in the participant's browser. While running an experiment offline, you won't be able to send the data to a database. However you can still see the data that jsPsych collects by saving it as a local file (using [`jsPsych.data.get().localSave`](../core_library/jspsych-data.md#localsave)), displaying it in the webpage at the end of the experiment (using [`jsPsych.data.displayData`](../core_library/jspsych-data.md#jspsychdatadisplaydata)), or printing it to the browser's console (using [`console.log`](https://www.w3schools.com/jsref/met_console_log.asp)).
Permanent data storage is also necessary when the code that runs the experiment depends on information that can't be known in advance, and that changes throughout data collection. Some common examples of this in cognitive behavioral research are **version counterbalancing**, where the experiment code needs to access and update the history of version assignment in order to determine which version should be assigned, and **multi-session/training studies**, where the experiment might need to access and update information about each participant like their current session number, task difficulty level, etc.
Doing these things in an automated way requires the use of a server. While developing and testing your experiment offline, you might choose to simulate some of these things and then implement them properly once you move your experiment online. For instance, you could [randomize](../core_library/jspsych-randomization.md#jspsychrandomizationsamplewithoutreplacement) instead of counterbalancing version assignment:
```js
var versions = [1,2];
var random_version = jsPsych.randomization.sampleWithoutReplacement(versions,1)[0];
```
And use [URL query parameters](../core_library/jspsych-data.md#jspsychdatageturlvariable) to pass in variables like session number and difficulty level:
```js
// add the variables onto the end of the URL that appears in the browser when you open the file
// e.g., file:///C:/my_experiment.html?id=1&sess=2&diff=3
var participant_id = jsPsych.data.getURLVariable('id');
var session = jsPsych.data.getURLVariable('sess');
var difficulty = jsPsych.data.getURLVariable('diff');
```
## Online
### Hosting the Experiment and Saving the Data
jsPsych is a front-end JavaScript library that runs entirely on the participant's computer. To run a jsPsych experiment over the internet, the files need to be hosted on a public web server so that participants can access the experiment using a web browser. When the participant completes the experiment in the browser, all of the data that jsPsych collects is stored on the participant's computer in the browser's memory. To get access to this data, it needs to be sent from the participant's browser back to the web server and stored in a database or a file.
To be maximally flexible, jsPsych doesn't provide a single built-in solution for the web server component of your experiment. This makes jsPsych compatible with a wide range of hosting services and tools, allowing researchers to choose the web server option that best suit their needs.
Some options for running your jsPsych experiment online include:
* [Cognition.run](https://www.cognition.run/) - A free service designed specifically for hosting jsPsych experiments, with an easy-to-use interface.
* [JATOS](https://www.jatos.org/Whats-JATOS.html) - A free program that runs on your own server and provides a GUI for setting up experiments and accessing the data. Offers lots of features for creating more complex experiments and managing multiple researchers.
* [Pavlovia](https://pavlovia.org/) - A paid hosting service for web-based experiments, run by the PsychoPy team. Experiment files are managed on a GitLab repository. Participants will access the experiment through a link to Pavlovia.
* [PsiTurk](https://psiturk.org/) - Python-based program to help you host your experiment on your own computer and collect data from MTurk (see Recruiting Participants below). Relatively easy for a DIY option.
* [Pushkin](https://languagelearninglab.gitbook.io/pushkin/) - A set of tools to help you set up your own virtual laboratory for online experiments. This option differs from the others in that it helps you set up a complete website that may contain many different experiments, information about the laboratory, participant logins, and other features that are targeted at hosting large-scale data collection efforts.
* Full DIY - You can setup your own web server and database and handle the communication yourself. Traditional web server 'stacks' include [LAMP](https://www.digitalocean.com/community/tutorial_collections/how-to-install-lamp)/[LEMP](https://www.digitalocean.com/community/tutorials/how-to-install-linux-nginx-mysql-php-lemp-stack-on-ubuntu-20-04) (Linux operating system, Apache or Nginx server application, MySQL database, and PHP programming language). Other common web server frameworks include [Flask](https://flask.palletsprojects.com/) (Python) and [Node.js](https://nodejs.org/) (JavaScript).
### Recruiting Participants
Once your experiment is running online, you could recruit participants in the same way that you would for lab-based studies. For instance, if your institution uses SONA, you can advertise your web-based study link on SONA. SONA allows you to automactically embed a unique ID in online study URLs, which you can then save in your data using [jsPsych's URL query parameters function](../core_library/jspsych-data.md#jspsychdatageturlvariable). SONA will also generate a completion URL that you can redirect participants to at the end of the study, and this will mark them as having completed the study in SONA.
To take full advantage of hosting an experiment online, many researchers advertise their experiments more widely. Social media and other media outlets provide one option for reaching a large number of potential participants. There are also some commercial platforms that you can use to advertise your study and pay anonymous online participants. These recruitment platforms charge a fee for use. The advantages of these platforms are that they handle the participant payments and allow you to specify pre-screening criteria. The most commonly used recruitment platforms in online behavioral research are:
* [Prolific](https://www.prolific.co/): An online labor market designed specifically for web-based research.
* [Amazon Mechanical Turk (MTurk)](https://www.mturk.com/): An online labor market designed for advertising paid 'human intelligence tasks'. This service was designed for use by commercial businesses but has been used by behavioral researchers for many years.
Like SONA, Prolific and MTurk use URL query parameters to get participant information, and redirection to specific URLs to mark participants as having finished the study. jsPsych includes [convenience functions for interacting with MTurk participants](../core_library/jspsych-turk.md). Information about integrating with Prolific can be found in the researcher support section of their website.

306
docs/overview/style.md Normal file
View File

@ -0,0 +1,306 @@
# Controlling Visual Appearance
Your experiment's style and formatting comes from the CSS (cascading style sheet) rules that are stored in the jspsych.css file, and the browser's defaults. There are a few ways to change the style and formatting in your experiment. The method that you choose is partly a matter of personal preference. It might also depend on whether you want the style/formatting change(s) to apply to _specific trials_, to _the whole experiment_ (HTML page), or across _different experiments_. This section discusses the different ways of incorporating CSS into your jsPsych experiment. You can also see [this page about adding CSS to web pages](https://www.w3schools.com/html/html_css.asp) to learn more.
## Inline CSS
Whenever you're using a parameter that accepts an HTML-formatted string, you have the option to include inline CSS. Inline CSS is a way of adding style and formatting directly into a specific HTML element using its ["style" attribute](https://www.w3schools.com/tags/att_style.asp). This is a good option for when you want to make few and/or simple style changes to an HTML trial parameter.
To change an element's style using inline CSS, you can set the element's "style" attribute to a string that contains the CSS parameters that you want to change, along with the values that you want to use. The syntax is " \<parameter-name> : \<parameter-value> ;".
In the example below, the stimulus font size is set to 30px and the text color is set to red. These changes will _only_ be applied to this stimulus text in this specific trial.
```javascript
var trial = {
type: 'html-keyboard-response',
stimulus: '<p style="font-size:30px;color:red;">hello world!</p>'
}
```
You can also use a [dynamic parameter]() to combine inline CSS and trial-specific variables. This allows you to easily apply the same inline CSS to multiple trials. Here's an example using a dynamic stimulus parameter and [timeline variables]():
```javascript
var trial = {
type: 'html-keyboard-response',
stimulus: function() {
var stim = '<p style="font-size:30px;font-weight:bold;">'+jsPsych.timelineVariable('text')+'</p>';
return stim;
}
}
var trial_procedure = {
timeline: [trial],
timeline_variables: [
{text: 'Welcome'},
{text: 'to'},
{text: 'the'},
{text: 'experiment!'}
]
}
```
## Adding CSS rules
You may want to add a lot of different CSS changes to your experiment, re-use the same change(s) across lots of different trials, and/or separate the style/formatting from the HTML string. In these cases, you might find it useful to create CSS rules rather than using inline CSS.
Creating CSS rules is a lot like using inline CSS, except that you also need to use a [CSS selector](https://www.w3schools.com/css/css_selectors.asp). This is because your CSS rules aren't attached to any specific HTML element (unlike inline CSS), so you need to tell the browser which element(s) the style rules should apply to. The syntax is "css-selector { \<parameter-name> : \<parameter-value> ; }".
In the example below, the CSS selector "p" tells the browser to apply the font size change to any text that is inside of a \<p> element.
```css
p {
font-size: 30px;
}
```
You can make more specific changes using CSS rules. The specificity will depend on the CSS selectors that are used. In addition to using the [tag name](https://www.w3schools.com/cssref/sel_element.asp) (e.g. "p"), other common CSS selectors include the element's [ID](https://www.w3schools.com/html/html_id.asp) or [class](https://www.w3schools.com/html/html_classes.asp). If you are selecting an element using it's ID, then the CSS selector needs to have a \# in front of the ID, e.g. "\#stimulus". If you are selecting elements based on their class, then you need to include a . in front of the class, e.g. ".large-text".
In the example below, the "#stimulus" CSS selector means that the width change will only affect elements with the "stimulus" ID, and the ".large-text" CSS selector means that the font size change will only affect elements that have the "large-text" class.
```css
#stimulus
width: 300px;
}
.large-text {
font-size: 200%;
}
```
It is possible to create even more specific CSS selectors, for instance by combining tags, IDs, and/or classes. For example, let's say that you are showing feedback text to participants, and that this text is inside of a \<p> tag. You could add the ID "correct" to the \<p> element for correct response feedback, and the ID "incorrect" to the \<p> element for incorrect response feedback. Then you can define separate styles for correct and incorrect feedback text like this:
```css
p#incorrect {
color: red;
}
p#correct {
color: green;
}
```
See [this page about CSS selectors](https://www.w3schools.com/cssref/css_selectors.asp) for a complete reference of CSS selector patterns and their meanings.
### With style tags
You can add CSS rules to your HTML page by putting them inside of \<style> tags. These rules will be applied to your _whole experiment_. This method can be useful for making general changes to the way that your experiment looks.
In the example below, the default font size is set to 25px throughout the experiment. This will overrule the default font size of 18px that is set in the jspsych.css file.
```html
<head>
<script src="jsPsych/jspsych.js"></script>
<script src="jsPsych/plugins/jspsych-html-keyboard-response.js"></script>
<link rel="stylesheet" href="jsPsych/css/jspsych.css">
<style>
.jspsych-display-element {
font-size: 25px;
}
</style>
</head>
```
### With a stylesheet
CSS rules can also be applied to your experiment with a link to an external CSS file. This is the same method that is usually used to apply the style from jspsych.css to an experiment. These rules will be applied to your _whole experiment_. You may find it useful to use a custom stylesheet when you want to re-use the same CSS rules across _multiple experiments_ (HTML files).
This example shows how to add a custom CSS file in addition to the styles provided in jspsych.css:
```html
<head>
<script src="jsPsych/jspsych.js"></script>
<script src="jsPsych/plugins/jspsych-image-keyboard-response.js"></script>
<link rel="stylesheet" href="jsPsych/css/jspsych.css">
<link rel="stylesheet" href="my_experiment_style.css">
</head>
```
Below are the some example contents of an external CSS file, like the "my_experiment_style.css" from the example above. This CSS will (1) change the page background color to black, (2) change the default font to 25px and white, and (3) limit the width of the page content so that it can only take up to 80% of its normal width.
```css
body {
background-color: black;
}
.jspsych-display-element {
font-size: 25px;
color: white;
}
.jspsych-content {
max-width: 80%;
}
```
Note that \<style> tags are not used inside of an external CSS file.
### Using the css_classes trial parameter
CSS rules can also be applied in a trial-specific way using the `css_classes` parameter. This parameter will apply one or more class to the \<div> element that holds all of the jsPsych page content during that specific trial. This way you can treat CSS styles just like any other trial parameter.
You can use a static `css_classes` parameter value if you always want to apply the same CSS rules to the trial. In the 'fixation' example below, separating the style rules from the `stimulus` string makes the code a little bit 'cleaner', and this makes it easier to re-use the same style rules in other parts of the experiment.
```html
<head>
<script src="jsPsych/jspsych.js"></script>
<script src="jsPsych/plugins/jspsych-html-keyboard-response.js"></script>
<link rel="stylesheet" href="jsPsych/css/jspsych.css">
<style>
.fixation {font-size: 90px; font-weight: bold; color: gray;}
</style>
</head>
<script>
var fixation = {
type: 'html-keyboard-response',
stimulus: '+',
choices: jsPsych.NO_KEYS,
trial_duration: 500,
css_classes: ['fixation']
}
// ...
</script>
```
You may want the `css_classes` parameter to vary across trials. If so, you can turn it into a [dynamic parameter]() or use [timeline variables]() (see examples below).
One thing to note about the `css_classes` parameter is that it only adds the class(es) to the jspsych-content \<div> element, which is the "parent" element that contains all of the experiment content. Often you'll want your CSS rules to be applied to other elements _inside_ of this jspsych-content div. Sometimes your CSS rules will be "inherited" by all of the other jsPsych content inside of this parent \<div>. For instance, in the `fixation` example above, the CSS rules that change the font size, weight and color are applied to the parent \<div> and automatically passed on to the stimulus text through inheritance.
There are two reasons why a CSS rule like the one above for `fixation` may not work the way you expect:
1. Not all CSS properties are inherited from the parent element**. **
2. When a CSS property is inherited from the parent element, it will affect _all_ elements in a given trial.
In these cases, you can change your CSS selector to make it more specific: add a space after class name, then add _more CSS selectors_ to select the specific element(s) that you want to change.
In the example below, the CSS selector `.left-align #stimulus` selects the element with the ID "stimulus" that is _inside_ of an element with the class "left-align".
```html
<head>
<script src="jsPsych/jspsych.js"></script>
<script src="jsPsych/plugins/jspsych-html-keyboard-response.js"></script>
<link rel="stylesheet" href="jsPsych/css/jspsych.css">
<style>
.left-align #stimulus {text-align: left; width: 600px;}
.right-align #stimulus {text-align: right; width: 600px;}
</style>
</head>
<script>
var trial_procedure = {
timeline: [{
type: 'html-keyboard-response',
stimulus: '<p id="stimulus">This is the stimulus.</p>',
prompt: '<p>This text will not be affected by the CSS classes '+
'because it does not have the "stimulus" ID.</p>',
css_classes: jsPsych.timelineVariable('css_classes')
}],
timeline_variables: [
{css_classes: ['left-align']},
{css_classes: ['right-align']}
]
}
// ...
</script>
```
It's also possible to pass multiple class names to the `css_classes` parameter. This can be useful for creating conditions that involve crossing different style-related factors. This example shows you to combine two text alignment and two text color factors to produce four different stimulus conditions:
```html
<head>
<script src="jsPsych/jspsych.js"></script>
<script src="jsPsych/plugins/jspsych-html-keyboard-response.js"></script>
<link rel="stylesheet" href="jsPsych/css/jspsych.css">
<style>
.left-align #stimulus {text-align: left; width: 600px;}
.right-align #stimulus {text-align: right; width: 600px;}
.teal #stimulus {color: teal;}
.purple #stimulus {color: purple;}
</style>
</head>
<script>
var trial_procedure = {
timeline: [{
type: 'html-keyboard-response',
stimulus: '<p id="stimulus">This is the stimulus.</p>',
prompt: '<p>This text will not be affected by the CSS classes '+
'because it does not have the "stimulus" ID.</p>',
css_classes: jsPsych.timelineVariable('css_classes'),
data: {condition: jsPsych.timelineVariable('condition')}
}],
timeline_variables: [
{css_classes: ['left-align','teal'], condition: 'left-teal'},
{css_classes: ['right-align','teal'], condition: 'right-teal'},
{css_classes: ['left-align','purple'], condition: 'left-purple'},
{css_classes: ['right-align','purple'], condition: 'right-purple'}
]
}
// ...
</script>
```
See the "css-classes-parameter.html" file in jsPsych's examples subfolder for more explanation and examples.
## Tips for working with CSS
Your browser's developer tools contain very useful features for exploring and debugging your experiment's style and formatting. Open your browser's developer tools and click on the Element Inspector button or go to the Elements tab. Once you have selected an element on the page, you can see all of the information that can be used to select it, including:
1. tag name, e.g., "div", "p", "img", "button"
2. ID, if it has one
3. class(es), if it has any
You can then use this information to create a CSS selector to modify that element's style.
![devtools-element-inspector](../img/devtools-inspect-element.png)
As you can see, jsPsych adds its own IDs and classes to many elements. You can use the developer tools to determine what IDs and classes already exist for the elements that you want to modify, as you may can often just use these instead of adding your own. For instance, in the "html-keyboard-response" plugin, the stimulus will always be shown in a \<div> with the ID "jspsych-html-keyboard-response-stimulus". So you can create a CSS rule that is applied to all "html-keyboard-response" stimuli like this:
```css
#jspsych-html-keyboard-response-stimulus {
color: white;
background-color: blue;
width: 100px;
border: 4px solid black;
}
```
As another example, most jsPsych buttons have the class "jspsych-btn", so you can use this class to change the default button styling:
```css
.jspsych-btn {
padding: 20px 20px;
font-size: 25px;
border-color: black;
}
```
You can also use the developer tools to change an element's CSS and immediately see the effect that the changes will have on the page. These changes are just temporary, so you will still need to use one of methods described above to add the CSS changes to your experiment. However, making changes in the developer tools is very useful for figuring out which CSS properties to change and which values to use. This area of the developer tools also shows what styles are currently applied to the element and where those style rules are coming from.
![devtools-change-css](../img/devtools-change-css.png)
There are a few things to be aware of while debugging problems with CSS.
1. When there are conflicting CSS rules, *some CSS rules will take precedence over others*. For instance, inline CSS usually takes precedence over other CSS rules, and more specific CSS selectors usually take precedence over less specific ones.
2. When there are conflicting CSS rules that have the same level of precedence, *the last rule will override any earlier rules*. For that reason it's important to add your own custom stylesheet _after_ the default jspsych.css stylesheet. See [this page about CSS precedence]() for more information.
If one CSS style rule is overridden by another one, the rule that is overridden will appear in ~~strikethrough text~~ in the element's "Styles" section. Also, if you are using an incorrect CSS property name or an invalid value, then that will show up here as an error, indicated by both ~~strikethrough text~~ and a little yellow warning symbol.
![devtools-css-error](../img/devtools-css-errors.png)

View File

@ -130,7 +130,8 @@ In the above version, there are four separate trials defined in the `timeline_va
What if we wanted the stimuli to be a little more complex, with a name displayed below each face? And let's add an additional step where the name is displayed prior to the face appearing. (Maybe this is one condition of an experiment investigating whether the order of name-face or face-name affects retention.)
To do this, we will need to use the `jsPsych.timelineVariable()` method in a slightly different way. Instead of using it as the parameter, we are going to create a dynamic parameter using a function and place the call to `jsPsych.timelineVariable()` inside this function. This will allow us to create an HTML string that has both the image and the name. Note that there is a subtle syntax difference: there is an extra parameter when `jsPsych.timelineVariable()` is called within a function. This `true` value causes the `jsPsych.timelineVariable()` to immediately return the value of the timeline variable. In a normal context, the function `jsPsych.timelineVariable()` returns a function. This is why `jsPsych.timelineVariable()` can be used directly as a parameter even though the parameter is dynamic.
This time, instead of using `jsPsych.timelineVariable()` as the stimulus parameter value, we are going to create a dynamic parameter (function), and place the call to `jsPsych.timelineVariable()` inside this function. This will allow us to create a parameter value that combines multiple bits of information, such as one or more of the values that change across trials (which come from the `timeline_variables` array), and/or anything that doesn't change across trials. In this example, we'll need to switch to using the "html-keyboard-response" plugin so that we can define the stimulus as a custom HTML string that contains an image and text (instead of just an image file). The value of the stimulus parameter will be a function that returns an HTML string that contains both the image and the name.
(Note: in previous versions of jsPsych, there's an extra `true` parameter that you must add when calling `jsPsych.timelineVariable()` from inside a function. As of jsPsych v6.3, `jsPsych.timelineVariable()` automatically detects the context in which it's called, so this additional `true` parameter is not required.)
```javascript
@ -151,8 +152,8 @@ var face_name_procedure = {
{
type: 'html-keyboard-response',
stimulus: function(){
var html="<img src='"+jsPsych.timelineVariable('face', true)+"'>";
html += "<p>"+jsPsych.timelineVariable('name', true)+"</p>";
var html="<img src='"+jsPsych.timelineVariable('face')+"'>";
html += "<p>"+jsPsych.timelineVariable('name')+"</p>";
return html;
},
choices: jsPsych.NO_KEYS,
@ -184,24 +185,6 @@ var face_name_procedure = {
}
```
### Repeating trials
If we want to repeat the set of trials multiple times, then we can set `repetitions` to an integer. If `randomize_order` is also `true`, the order will re-randomize before every repetition.
```javascript
var face_name_procedure = {
// timeline parameter hidden to save space ...
timeline_variables: [
{ face: 'person-1.jpg', name: 'Alex' },
{ face: 'person-2.jpg', name: 'Beth' },
{ face: 'person-3.jpg', name: 'Chad' },
{ face: 'person-4.jpg', name: 'Dave' }
],
randomize_order: true,
repetitions: 3
}
```
### Sampling methods
There are also a set of sampling methods that can be used to select a set of trials from the timeline_variables. Sampling is declared by creating a `sample` parameter. The `sample` parameter is given an object of arguments. The `type` parameter in this object controls the type of sampling that is done. Valid values for `type` are
@ -324,9 +307,41 @@ var face_name_procedure = {
}
```
## Repeating a set of trials
To repeat a timeline multiple times, you can create an object (node) that contains a `timeline`, which is the timeline array to repeat, and `repetitions`, which is the number of times to repeat that timeline.
```javascript
var trial = {
type: 'html-keyboard-response',
stimulus: 'This trial will be repeated twice.'
}
var node = {
timeline: [trial],
repetitions: 2
}
```
The `repetitions` parameter can be used alongside other node parameters, such as timeline variables, loop functions, and/or conditional functions. If you are using `timeline_variables` and `randomize_order` is `true`, then the order of the timeline variables will re-randomize before every repetition.
```javascript
var face_name_procedure = {
// timeline parameter hidden to save space ...
timeline_variables: [
{ face: 'person-1.jpg', name: 'Alex' },
{ face: 'person-2.jpg', name: 'Beth' },
{ face: 'person-3.jpg', name: 'Chad' },
{ face: 'person-4.jpg', name: 'Dave' }
],
randomize_order: true,
repetitions: 3
}
```
## Looping timelines
Any timeline can be looped using the `loop_function` option. The loop function should be a function that evaluates to `true` if the timeline should repeat, and `false` if the timeline should end. It receives a single parameter: the DataCollection object with all of the data from the trials executed in the last iteration of the timeline. The loop function will be evaluated after the timeline is completed.
Any timeline can be looped using the `loop_function` option. The loop function should be a function that evaluates to `true` if the timeline should repeat, and `false` if the timeline should end. It receives a single parameter, named `data` by convention. This parameter will be the [DataCollection object](/core_library/jspsych-data/#datacollection) with all of the data from the trials executed in the last iteration of the timeline. The loop function will be evaluated after the timeline is completed.
```javascript
var trial = {
@ -337,7 +352,7 @@ var trial = {
var loop_node = {
timeline: [trial],
loop_function: function(data){
if(jsPsych.pluginAPI.convertKeyCharacterToKeyCode('r') == data.values()[0].key_press){
if(data.values()[0].response == 'r'){
return true;
} else {
return false;
@ -367,7 +382,7 @@ var if_node = {
// get the data from the previous trial,
// and check which key was pressed
var data = jsPsych.data.get().last(1).values()[0];
if(data.key_press == jsPsych.pluginAPI.convertKeyCharacterToKeyCode('s')){
if(data.response == 's'){
return false;
} else {
return true;
@ -385,3 +400,58 @@ jsPsych.init({
on_finish: function(){jsPsych.data.displayData(); }
});
```
## Timeline start and finish functions
You can run a custom function at the start and end of a timeline node using the `on_timeline_start` and `on_timeline_finish` callback function parameters. These are functions that will run when the timeline starts and ends, respectively.
```javascript
var procedure = {
timeline: [trial_1, trial_2],
on_timeline_start: function() {
console.log('The trial procedure just started.')
},
on_timeline_finish: function() {
console.log('The trial procedure just finished.')
}
}
```
This works the same way with timeline variables. The `on_timeline_start` and `on_timeline_finish` functions will run when timeline variables trials start and end, respectively.
```javascript
var face_name_procedure = {
// timeline parameter hidden to save space ...
timeline_variables: [
{ face: 'person-1.jpg', name: 'Alex' },
{ face: 'person-2.jpg', name: 'Beth' },
{ face: 'person-3.jpg', name: 'Chad' },
{ face: 'person-4.jpg', name: 'Dave' }
],
randomize_order: true,
on_timeline_start: function() {
console.log('First trial is starting.')
},
on_timeline_finish: function() {
console.log('Last trial just finished.')
}
}
```
When the `repetititons` option is used (and is greater than 1), these functions will run once per repetition of the timeline.
```javascript
var repetition_count = 0;
var procedure = {
timeline: [trial_1, trial_2],
repetitions: 3,
on_timeline_start: function() {
repetition_count++;
console.log('Repetition number ',repetition_count,' has just started.');
},
on_timeline_finish: function() {
console.log('Repetition number ',repetition_count,' has just finished.')
}
}
```

View File

@ -1,142 +0,0 @@
# Advanced Options for Trials
The parameters available for a trial depend primarily on what plugin is used for the trial. However, there are several options that do not depend on the particular plugin; they are available for all trials.
## The data parameter
The `data` parameter enables tagging the trial with additional properties. This can be useful for storing properties of the trial that are not directly apparent from the values that the plugin records. The `data` parameter value should be an object that contains key-value pairs.
A simple example is the [Flanker Task](https://en.wikipedia.org/wiki/Eriksen_flanker_task). In this experiment, participants respond to the direction of an arrow, pressing a key to the left for a left-pointing arrow (<) and a key to the right for a right-pointing arrow (>). The arrow appears in the center of *flankers*, or arrows that the participant should ignore. Those flankers can be congruent (>>>>>) or incongruent (<<><<).
A trial for the Flanker Task written with jsPsych might look like this:
```javascript
var trial = {
type: 'html-keyboard-response',
stimulus: '<<<<<',
choices: ['f','j'],
data: {
stimulus_type: 'congruent',
target_direction: 'left'
}
}
```
Note the use of the data parameter to add a property `stimulus_type` with the value `congruent` and a property `target_direction` with the value `left`. Having these properties recorded directly in the data simplifies data analysis, making it easy to aggregate data by `stimulus_type` and/or `target_direction`.
## Inter-trial interval
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 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.
```javascript
var trial = {
type: 'html-keyboard-response',
stimulus: 'There will be a 1.5 second blank screen after this trial.',
post_trial_gap: 1500
}
```
## The on_start event
Immediately before a trial runs, there is an opportunity to run an arbitrary function through the `on_start` event handler. This event handler is passed a single argument containing an *editable* copy of the trial parameters. This event handler can therefore be used to alter the trial based on the state of the experiment, among other uses.
```javascript
var trial = {
type: 'html-keyboard-response',
stimulus: '<<<<<',
choices: ['f','j'],
data: {
stimulus_type: 'congruent',
target_direction: 'left'
},
on_start: function(trial){
trial.stimulus = '<<><<';
trial.data.stimulus_type = 'incongruent';
}
}
```
## The on_finish event
After a trial is completed, there is an opportunity to run an arbitrary function through the `on_finish` event handler. This event handler is passed a single argument containing an *editable* copy of the data recorded for that trial. This event handler can therefore be used to update the state of the experiment based on the data collected or modify the data collected.
This can be useful to calculate new data properties that were unknowable at the start of the trial. For example, with the Flanker Task example above, the `on_finish` event could add a new property `correct`.
```javascript
var trial = {
type: 'html-keyboard-response',
stimulus: '<<<<<',
choices: ['f','j'],
data: {
stimulus_type: 'congruent',
target_direction: 'left'
},
on_finish: function(data){
if(data.key_press == 70){// 70 is the numeric code for f
data.correct = true; // can add property correct by modify data object directly
} else {
data.correct = false;
}
}
}
```
## The on_load event
The `on_load` callback can be added to any trial. The callback will trigger once the trial has completed loading. For most plugins, this will occur once the display has been initially updated but before any user interactions or timed events (e.g., animations) have occurred.
#### Sample use
```javascript
var trial = {
type: 'image-keyboard-response',
stimulus: 'imgA.png',
on_load: function() {
console.log('The trial just finished loading.');
}
};
```
## Dynamic parameters
Most plugins allow parameters to be functions. In a typical declaration of a jsPsych trial, parameters have to be known at the start of the experiment. This makes it impossible to alter the content of the trial based on the outcome of previous trials. When functions are used as parameters for a block of trials, the function is evaluated at the start of each trial, and the return value of the function is used as the parameter. This enables dynamic updating of the parameter based on data that a subject has generated.
Here is a sketch of how this functionality could be used to display feedback to a subject in the Flanker Task.
```javascript
var timeline = [];
var trial = {
type: 'html-keyboard-response',
stimulus: '<<<<<',
choices: ['f','j'],
data: {
stimulus_type: 'congruent',
target_direction: 'left'
},
on_finish: function(data){
if(data.key_press == 70){// 70 is the numeric code for f
data.correct = true; // can add property correct by modify data object directly
} else {
data.correct = false;
}
}
}
var feedback = {
type: 'html-keyboard-response',
stimulus: function(){
var last_trial_correct = jsPsych.data.get().last(1).values()[0].correct;
if(last_trial_correct){
return "<p>Correct!</p>";
} else {
return "<p>Wrong.</p>"
}
}
}
timeline.push(trial, feedback);
```

View File

@ -1,79 +0,0 @@
# Creating a new plugin
Creating new plugins is the way to add new kinds of tasks to jsPsych. A task can be virtually any kind of activity. If it can be implemented in JavaScript, then it almost certainly can be turned into a plugin.
## What's in a plugin file?
Plugin files follow a specific template. Adherence to the template is what allows jsPsych to run a plugin without knowing anything about what the plugin is doing. What makes plugins so flexible is that the template imposes very few requirements on the code. Here's what an empty plugin template looks like:
```
jsPsych.plugins['plugin-name'] = (function(){
var plugin = {};
plugin.info = {
name: 'plugin-name',
parameters: {
}
}
plugin.trial = function(display_element, trial){
jsPsych.finishTrial();
}
return plugin;
})();
```
This plugin will work! It defines a plugin called 'plugin-name', and it does absolutely nothing. However, it won't break the experiment, and jsPsych will understand that this is a valid plugin.
Let's examine it in more detail.
The overall structure of the plugin is defined using a module JavaScript design pattern. This pattern uses a technique called an anonymous closure. This is why the first line has `(function(){` and the last line is `})();`. The details aren't important, but if you want to learn more about it, [this is a nice overview](http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html). The reason this pattern is useful is because it allows for persistent state and private scope. In other words, the plugin is isolated and can't be altered by other plugins.
The module, created by the `(function(){` `})();` expressions, contains an object called `plugin` that has two properties, `info` and `trial`. The `plugin` object is returned at the end of the module, which is what assigns the defined properties of `plugin` to `jsPsych['plugin-name']`.
### plugin.trial
The `trial` method is responsible for running a single trial. There are two parameters that are passed into the trial method. The first, `display_element`, is the DOM element where jsPsych content is being rendered. This parameter will be an `HTMLElement`. Generally, you don't need to worry about this parameter being in the correct format, and can assume that it is an `HMTLElement` and use methods of that class. The second, `trial`, is an object containing all of the parameters specified in the corresponding TimelineNode.
The only requirement for the `trial` method is that it calls `jsPsych.finishTrial()` when it is done. This is how jsPsych knows to advance to the next trial in the experiment (or end the experiment if it is the last trial). The plugin can do whatever it needs to do before that point.
Of course, there are other things that you will probably want the plugin to do besides just end. Here are some examples:
#### Change the content of the display
There are a few ways to change the content of the display. The `display_element` parameter of the trial method contains the DOM element for displaying content, so you can use various JavaScript methods for interaction with the display element. A common one is to change the `innerHTML`.
```javascript
var html_content = '<p>This is the first paragraph</p>';
html_content += '<p>This is the second paragraph</p>';
display_element.innerHTML = html_content;
```
It is often appropriate to use `innerHTML` to clear the display at the end of a trial:
```javascript
// clear the display
display_element.innerHTML = '';
```
#### Write data
Plugins exist to collect data, so saving data is obviously a crucial thing to do. You can pass an object of data as the parameter to `jsPsych.finishTrial()`:
```javascript
var data = {
correct: true,
rt: 350
}
jsPsych.finishTrial(data)
```
The data recorded will be that `correct` is `true` and that `rt` is `350`. Additional data for the trial will also be collected automatically by the jsPsych library.
## The plugin template
An empty plugin template is included in the `plugins/template` folder.

View File

@ -4,7 +4,7 @@ This plugin displays a sequence of images at a fixed frame rate. The sequence ca
## Parameters
Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
@ -12,18 +12,18 @@ stimuli | array | *undefined* | Each element of the array is a path to an image
frame_time | numeric | 250 | How long to display each image (in milliseconds).
frame_isi | numeric | 0 | If greater than 0, then a gap will be shown between each image in the sequence. This parameter specifies the length of the gap.
sequence_reps | numeric | 1 | How many times to show the entire sequence. There will be no gap (other than the gap specified by `frame_isi`) between repetitions.
choices | array of keycodes | `jsPsych.ALL_KEYS` | This array contains the keys that the subject is allowed to press in order to respond to the stimulus. Keys can be specified as their [numeric key code](http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes) or as characters (e.g., `'a'`, `'q'`). The default value of `jsPsych.ALL_KEYS` means that all keys will be accepted as valid responses. Specifying `jsPsych.NO_KEYS` will mean that no responses are allowed.
choices | array of strings | `jsPsych.ALL_KEYS` | This array contains the key(s) that the subject is allowed to press in order to respond to the stimulus. Keys should be specified as characters (e.g., `'a'`, `'q'`, `' '`, `'Enter'`, `'ArrowDown'`) - see [this page](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values) and [this page (event.key column)](https://www.freecodecamp.org/news/javascript-keycode-list-keypress-event-key-codes/) for more examples. Any key presses that are not listed in the array will be ignored. The default value of `jsPsych.ALL_KEYS` means that all keys will be accepted as valid responses. Specifying `jsPsych.NO_KEYS` will mean that no responses are allowed.
prompt | string | null | This string can contain HTML markup. Any content here will be displayed below the stimulus. The intention is that it can be used to provide a reminder about the action the subject is supposed to take (e.g., which key(s) to press).
render_on_canvas | boolean | true | If true, the images will be drawn onto a canvas element. This prevents a blank screen (white flash) between consecutive images in some browsers, like Firefox and Edge. If false, the image will be shown via an img element, as in previous versions of jsPsych.
## Data Generated
In addition to the [default data collected by all plugins](overview#datacollectedbyplugins), this plugin collects the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
animation_sequence | JSON | An array, encoded in JSON format. Each element of the array is an object that represents a stimulus in the animation sequence. Each object has a `stimulus` property, which is the image that was displayed, and a `time` property, which is the time in ms, measured from when the sequence began, that the stimulus was displayed.
responses | JSON | An array, encoded in JSON format. Each element of the array is an object representing a response given by the subject. Each object has a `stimulus` property, indicating which image was displayed when the key was pressed, an `rt` property, indicating the time of the key press relative to the start of the animation, and a `key_press` property, indicating which key was pressed.
animation_sequence | array | An array, where each element is an object that represents a stimulus in the animation sequence. Each object has a `stimulus` property, which is the image that was displayed, and a `time` property, which is the time in ms, measured from when the sequence began, that the stimulus was displayed. The array will be encoded in JSON format when data is saved using either the `.json()` or `.csv()` functions.
response | array | An array, where each element is an object representing a response given by the subject. Each object has a `stimulus` property, indicating which image was displayed when the key was pressed, an `rt` property, indicating the time of the key press relative to the start of the animation, and a `key_press` property, indicating which key was pressed. The array will be encoded in JSON format when data is saved using either the `.json()` or `.csv()` functions.
## Examples

View File

@ -4,34 +4,35 @@ This plugin plays audio files and records responses generated with a button clic
If the browser supports it, audio files are played using the WebAudio API. This allows for reasonably precise timing of the playback. The timing of responses generated is measured against the WebAudio specific clock, improving the measurement of response times. If the browser does not support the WebAudio API, then the audio file is played with HTML5 audio.
Audio files are automatically preloaded by jsPsych. However, if you are using timeline variables or another dynamic method to specify the audio stimulus you will need to [manually preload](/overview/media-preloading/#manual-preloading) the audio.
Audio files can be automatically preloaded by jsPsych using the [`preload` plugin](jspsych-preload.md). However, if you are using timeline variables or another dynamic method to specify the audio stimulus, you will need to [manually preload](/overview/media-preloading/#manual-preloading) the audio.
The trial can end when the subject responds, when the audio file has finished playing, or if the subject has failed to respond within a fixed length of time.
The trial can end when the subject responds, when the audio file has finished playing, or if the subject has failed to respond within a fixed length of time. You can also prevent a button response from being made before the audio has finished playing.
## Parameters
Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
stimulus | audio file | undefined | Path to audio file to be played.
choices | array of strings | [] | Labels for the buttons. Each different string in the array will generate a different button.
button_html | HTML string | `'<button class="jspsych-btn">%choice%</button>'` | A template of HTML for generating the button elements. You can override this to create customized buttons of various kinds. The string `%choice%` will be changed to the corresponding element of the `choices` array. You may also specify an array of strings, if you need different HTML to render for each button. If you do specify an array, the `choices` array and this array must have the same length. The HTML from position 0 in the `button_html` array will be used to create the button for element 0 in the `choices` array, and so on.
prompt | string | null | This string can contain HTML markup. Any content here will be displayed below the stimulus. The intention is that it can be used to provide a reminder about the action the subject is supposed to take (e.g., which key to press).
trial_duration | numeric | null | How long to wait for the subject to make a response before ending the trial in milliseconds. If the subject fails to make a response before this timer is reached, the subject's response will be recorded as null for the trial and the trial will end. If the value of this parameter is null, the trial will wait for a response indefinitely.
margin_vertical | string | '0px' | Vertical margin of the button(s).
margin_horizontal | string | '8px' | Horizontal margin of the button(s).
response_ends_trial | boolean | true | If true, then the trial will end whenever the subject makes a response (assuming they make their response before the cutoff specified by the `trial_duration` parameter). If false, then the trial will continue until the value for `timing_response` is reached. You can use this parameter to force the subject to view a stimulus for a fixed amount of time, even if they respond before the time is complete.
trial_ends_after_audio | boolean | false | If true, then the trial will end as soon as the audio file finishes playing.
| Parameter | Type | Default Value | Description |
| ------------------------------ | ---------------- | ---------------------------------------- | ---------------------------------------- |
| stimulus | audio file | *undefined* | Path to audio file to be played. |
| choices | array of strings | *undefined* | Labels for the buttons. Each different string in the array will generate a different button. |
| button_html | HTML string | `'<button class="jspsych-btn">%choice%</button>'` | A template of HTML for generating the button elements. You can override this to create customized buttons of various kinds. The string `%choice%` will be changed to the corresponding element of the `choices` array. You may also specify an array of strings, if you need different HTML to render for each button. If you do specify an array, the `choices` array and this array must have the same length. The HTML from position 0 in the `button_html` array will be used to create the button for element 0 in the `choices` array, and so on. |
| prompt | string | null | This string can contain HTML markup. Any content here will be displayed below the stimulus. The intention is that it can be used to provide a reminder about the action the subject is supposed to take (e.g., which key to press). |
| trial_duration | numeric | null | How long to wait for the subject to make a response before ending the trial in milliseconds. If the subject fails to make a response before this timer is reached, the subject's response will be recorded as null for the trial and the trial will end. If the value of this parameter is null, the trial will wait for a response indefinitely. |
| margin_vertical | string | '0px' | Vertical margin of the button(s). |
| margin_horizontal | string | '8px' | Horizontal margin of the button(s). |
| response_ends_trial | boolean | true | If true, then the trial will end whenever the subject makes a response (assuming they make their response before the cutoff specified by the `trial_duration` parameter). If false, then the trial will continue until the value for `trial_duration` is reached. You can set this parameter to `false` to force the subject to listen to the stimulus for a fixed amount of time, even if they respond before the time is complete. |
| trial_ends_after_audio | boolean | false | If true, then the trial will end as soon as the audio file finishes playing. |
| response_allowed_while_playing | boolean | true | If true, then responses are allowed while the audio is playing. If false, then the audio must finish playing before the button choices are enabled and a response is accepted. Once the audio has played all the way through, the buttons are enabled and a response is allowed (including while the audio is being re-played via on-screen playback controls). |
## Data Generated
In addition to the [default data collected by all plugins](overview#datacollectedbyplugins), this plugin collects the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the stimulus first appears on the screen until the subject's response.
button_pressed | numeric | Indicates which button the subject pressed. The first button in the `choices` array is 0, the second is 1, and so on.
| Name | Type | Value |
| -------------- | ------- | ---------------------------------------- |
| rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the stimulus first began playing until the subject's response. |
| response | numeric | Indicates which button the subject pressed. The first button in the `choices` array is 0, the second is 1, and so on. |
## Examples

View File

@ -4,32 +4,33 @@ This plugin plays audio files and records responses generated with the keyboard.
If the browser supports it, audio files are played using the WebAudio API. This allows for reasonably precise timing of the playback. The timing of responses generated is measured against the WebAudio specific clock, improving the measurement of response times. If the browser does not support the WebAudio API, then the audio file is played with HTML5 audio.
Audio files are automatically preloaded by jsPsych. However, if you are using timeline variables or another dynamic method to specify the audio stimulus you will need to [manually preload](/overview/media-preloading/#manual-preloading) the audio.
Audio files can be automatically preloaded by jsPsych using the [`preload` plugin](jspsych-preload.md). However, if you are using timeline variables or another dynamic method to specify the audio stimulus, then you will need to [manually preload](/overview/media-preloading/#manual-preloading) the audio.
The trial can end when the subject responds, when the audio file has finished playing, or if the subject has failed to respond within a fixed length of time.
The trial can end when the subject responds, when the audio file has finished playing, or if the subject has failed to respond within a fixed length of time. You can also prevent a keyboard response from being recorded before the audio has finished playing.
## Parameters
Parameters with a default value of undefined must be specified. Other parameters can be left unspecified if the default value is acceptable.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of undefined must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
stimulus | audio file | undefined | Path to audio file to be played.
choices | array of keycodes | `jsPsych.ALL_KEYS` | This array contains the keys that the subject is allowed to press in order to respond to the stimulus. Keys can be specified as their [numeric key code](http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes) or as characters (e.g., `'a'`, `'q'`). The default value of `jsPsych.ALL_KEYS` means that all keys will be accepted as valid responses. Specifying `jsPsych.NO_KEYS` will mean that no responses are allowed.
prompt | string | null | This string can contain HTML markup. Any content here will be displayed below the stimulus. The intention is that it can be used to provide a reminder about the action the subject is supposed to take (e.g., which key to press).
trial_duration | numeric | null | How long to wait for the subject to make a response before ending the trial in milliseconds. If the subject fails to make a response before this timer is reached, the subject's response will be recorded as null for the trial and the trial will end. If the value of this parameter is null, then the trial will wait for a response indefinitely.
response_ends_trial | boolean | true | If true, then the trial will end whenever the subject makes a response (assuming they make their response before the cutoff specified by the `timing_response` parameter). If false, then the trial will continue until the value for `trial_duration` is reached. You can use this parameter to force the subject to view a stimulus for a fixed amount of time, even if they respond before the time is complete.
trial_ends_after_audio | boolean | false | If true, then the trial will end as soon as the audio file finishes playing.
| Parameter | Type | Default Value | Description |
| ------------------------------ | ---------------- | ------------------ | ---------------------------------------- |
| stimulus | audio file | undefined | Path to audio file to be played. |
| choices | array of strings | `jsPsych.ALL_KEYS` | This array contains the key(s) that the subject is allowed to press in order to respond to the stimulus. Keys should be specified as characters (e.g., `'a'`, `'q'`, `' '`, `'Enter'`, `'ArrowDown'`) - see [this page](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values) and [this page (event.key column)](https://www.freecodecamp.org/news/javascript-keycode-list-keypress-event-key-codes/) for more examples. Any key presses that are not listed in the array will be ignored. The default value of `jsPsych.ALL_KEYS` means that all keys will be accepted as valid responses. Specifying `jsPsych.NO_KEYS` will mean that no responses are allowed. |
| prompt | string | null | This string can contain HTML markup. Any content here will be displayed below the stimulus. The intention is that it can be used to provide a reminder about the action the subject is supposed to take (e.g., which key to press). |
| trial_duration | numeric | null | How long to wait for the subject to make a response before ending the trial in milliseconds. If the subject fails to make a response before this timer is reached, the subject's response will be recorded as null for the trial and the trial will end. If the value of this parameter is null, then the trial will wait for a response indefinitely. |
| response_ends_trial | boolean | true | If true, then the trial will end whenever the subject makes a response (assuming they make their response before the cutoff specified by the `trial_duration` parameter). If false, then the trial will continue until the value for `trial_duration` is reached. You can use set this parameter to `false` to force the subject to listen to the stimulus for a fixed amount of time, even if they respond before the time is complete. |
| trial_ends_after_audio | boolean | false | If true, then the trial will end as soon as the audio file finishes playing. |
| response_allowed_while_playing | boolean | true | If true, then responses are allowed while the audio is playing. If false, then the audio must finish playing before a keyboard response is accepted. Once the audio has played all the way through, a valid keyboard response is allowed (including while the audio is being re-played via on-screen playback controls). |
## Data Generated
In addition to the [default data collected by all plugins](overview#datacollectedbyplugins), this plugin collects the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
key_press | numeric | Indicates which key the subject pressed. The value is the [numeric key code](http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes) corresponding to the subject's response.
rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the stimulus first appears on the screen until the subject's response.
stimulus | string | Path to the audio file that played during the trial.
| Name | Type | Value |
| --------- | ------- | ---------------------------------------- |
| response | string | Indicates which key the subject pressed. If no key was pressed before the trial ended, then the value will be `null`. |
| rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the stimulus first began playing until the subject made a key response. If no key was pressed before the trial ended, then the value will be `null`. |
| stimulus | string | Path to the audio file that played during the trial. |
## Examples
@ -41,7 +42,7 @@ var trial = {
stimulus: 'sound/tone.mp3',
choices: ['e', 'i'],
prompt: "<p>Is the pitch high or low? Press 'e' for low and 'i' for high.</p>",
response_ends_trial: false
response_ends_trial: false
};
```

View File

@ -2,40 +2,42 @@
This plugin plays an audio file and allows the subject to respond by dragging a slider.
If the browser supports it, audio files are played using the WebAudio API.This allows for reasonably precise timing of the playback. The timing of responses generated is measured against the WebAudio specific clock, improving the measurement of response times. If the browser does not support the WebAudio API, then the audio file is played with HTML5 audio.
If the browser supports it, audio files are played using the WebAudio API. This allows for reasonably precise timing of the playback. The timing of responses generated is measured against the WebAudio specific clock, improving the measurement of response times. If the browser does not support the WebAudio API, then the audio file is played with HTML5 audio.
Audio files are automatically preloaded by jsPsych. However, if you are using timeline variables or another dynamic method to specify the audio stimulus you will need to [manually preload](/overview/media-preloading/#manual-preloading) the audio.
Audio files can be automatically preloaded by jsPsych using the [`preload` plugin](jspsych-preload.md). However, if you are using timeline variables or another dynamic method to specify the audio stimulus, then you will need to [manually preload](/overview/media-preloading/#manual-preloading) the audio.
The trial can end when the subject responds, or if the subject has failed to respond within a fixed length of time.
The trial can end when the subject responds, or if the subject has failed to respond within a fixed length of time. You can also prevent the slider response from being made before the audio has finished playing.
## Parameters
Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
stimulus | audio file | *undefined* | Audio file to be played
labels | array of strings | Labels displayed at equidistant locations on the slider. For example, two labels will be placed at the ends of the slider. Three labels would place two at the ends and one in the middle. Four will place two at the ends, and the other two will be at 33% and 67% of the slider width.
button_label | string | 'Continue' | Label of the button to end the trial.
min | integer | 0 | Sets the minimum value of the slider
max | integer | 100 | Sets the maximum value of the slider
start | integer | 50 | Sets the starting value of the slider
step | integer | 1 | Sets the step of the slider. This is the smallest amount by which the slider can change.
slider_width | integer | null | Set the width of the slider in pixels. If left null, then the width will be equal to the widest element in the display.
require_movement | boolean | false | If true, the subject must move the slider before clicking the continue button.
prompt | string | null | This string can contain HTML markup. Any content here will be displayed below the stimulus. The intention is that it can be used to provide a reminder about the action the subject is supposed to take (e.g., which key to press).
trial_duration | numeric | null | How long to wait for the subject to make a response before ending the trial in milliseconds. If the subject fails to make a response before this timer is reached, the subject's response will be recorded as null for the trial and the trial will end. If the value of this parameter is null, then the trial will wait for a response indefinitely.
response_ends_trial | boolean | true | If true, then the trial will end whenever the subject makes a response (assuming they make their response before the cutoff specified by the `timing_response` parameter). If false, then the trial will continue until the value for `trial_duration` is reached. You can use this parameter to force the subject to listen to the stimulus for a fixed amount of time, even if they respond before the time is complete.
| Parameter | Type | Default Value | Description |
| ------------------------------ | ---------------- | ------------- | ---------------------------------------- |
| stimulus | audio file | *undefined* | Audio file to be played |
| labels | array of strings | [] | Labels displayed at equidistant locations on the slider. For example, two labels will be placed at the ends of the slider. Three labels would place two at the ends and one in the middle. Four will place two at the ends, and the other two will be at 33% and 67% of the slider width. |
| button_label | string | 'Continue' | Label of the button to end the trial. |
| min | integer | 0 | Sets the minimum value of the slider |
| max | integer | 100 | Sets the maximum value of the slider |
| slider_start | integer | 50 | Sets the starting value of the slider |
| step | integer | 1 | Sets the step of the slider. This is the smallest amount by which the slider can change. |
| slider_width | integer | null | Set the width of the slider in pixels. If left null, then the width will be equal to the widest element in the display. |
| require_movement | boolean | false | If true, the subject must move the slider before clicking the continue button. |
| prompt | string | null | This string can contain HTML markup. Any content here will be displayed below the stimulus. The intention is that it can be used to provide a reminder about the action the subject is supposed to take (e.g., which key to press). |
| trial_duration | numeric | null | How long to wait for the subject to make a response before ending the trial in milliseconds. If the subject fails to make a response before this timer is reached, the subject's response will be recorded as null for the trial and the trial will end. If the value of this parameter is null, then the trial will wait for a response indefinitely. |
| response_ends_trial | boolean | true | If true, then the trial will end whenever the subject makes a response (assuming they make their response before the cutoff specified by the `trial_duration` parameter). If false, then the trial will continue until the value for `trial_duration` is reached. You can set this parameter to `false` to force the subject to listen to the stimulus for a fixed amount of time, even if they respond before the time is complete. |
| response_allowed_while_playing | boolean | true | If true, then responses are allowed while the audio is playing. If false, then the audio must finish playing before the slider is enabled and the trial can end via the next button click. Once the audio has played all the way through, the slider is enabled and a response is allowed (including while the audio is being re-played via on-screen playback controls). |
## Data Generated
In addition to the [default data collected by all plugins](overview#datacollectedbyplugins), this plugin collects the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
response | numeric | The numeric value of the slider.
rt | numeric | The time in milliseconds for the subject to make a response. The time is measured from when the stimulus first appears on the screen until the subject's response.
stimulus | string | The path of the audio file that was played.
| Name | Type | Value |
| ------------ | ------- | ---------------------------------------- |
| response | numeric | The numeric value of the slider. |
| rt | numeric | The time in milliseconds for the subject to make a response. The time is measured from when the stimulus first began playing until the subject's response. |
| stimulus | string | The path of the audio file that was played. |
| slider_start | numeric | The starting value of the slider. |
## Examples

View File

@ -6,7 +6,7 @@ The function cannot take any arguments. If arguments are needed, then an anonymo
## Parameters
Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
@ -16,7 +16,7 @@ async | boolean | `false` | Set to true if `func` is an asynchoronous function.
## Data Generated
In addition to the [default data collected by all plugins](overview#datacollectedbyplugins), this plugin collects the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------

View File

@ -0,0 +1,66 @@
# jspsych-canvas-button-response
This plugin can be used to draw a stimulus on a [HTML canvas element](https://www.w3schools.com/html/html5_canvas.asp), and record a button click response and response time. The canvas stimulus can be useful for displaying dynamic, parametrically-defined graphics, and for controlling the positioning of multiple graphical elements (shapes, text, images). The stimulus can be displayed until a response is given, or for a pre-determined amount of time. The trial can be ended automatically if the subject has failed to respond within a fixed length of time. One or more button choices will be displayed under the canvas, and the button style can be customized using HTML formatting.
## Parameters
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
stimulus | function | *undefined* | The function to draw on the canvas. This function automatically takes a canvas element as its only argument, e.g. `function(c) {...}` or `function drawStim(c) {...}`, where `c` refers to the canvas element. Note that the stimulus function will still generally need to set the correct context itself, using a line like `let ctx = c.getContext("2d")`.
canvas_size | array | [500, 500] | Array that defines the size of the canvas element in pixels. First value is height, second value is width.
choices | array of strings | [] | Labels for the buttons. Each different string in the array will generate a different button.
button_html | HTML string | `'<button class="jspsych-btn">%choice%</button>'` | A template of HTML for generating the button elements. You can override this to create customized buttons of various kinds. The string `%choice%` will be changed to the corresponding element of the `choices` array. You may also specify an array of strings, if you need different HTML to render for each button. If you do specify an array, the `choices` array and this array must have the same length. The HTML from position 0 in the `button_html` array will be used to create the button for element 0 in the `choices` array, and so on.
prompt | string | null | This string can contain HTML markup. Any content here will be displayed below the stimulus. The intention is that it can be used to provide a reminder about the action the subject is supposed to take (e.g., what question to answer).
trial_duration | numeric | null | How long to wait for the subject to make a response before ending the trial in milliseconds. If the subject fails to make a response before this timer is reached, the subject's response will be recorded as null for the trial and the trial will end. If the value of this parameter is null, the trial will wait for a response indefinitely.
stimulus_duration | numeric | null | How long to display the stimulus in milliseconds. The visibility CSS property of the stimulus will be set to `hidden` after this time has elapsed. If this is null, then the stimulus will remain visible until the trial ends.
margin_vertical | string | '0px' | Vertical margin of the button(s).
margin_horizontal | string | '8px' | Horizontal margin of the button(s).
response_ends_trial | boolean | true | If true, then the trial will end whenever the subject makes a response (assuming they make their response before the cutoff specified by the `trial_duration` parameter). If false, then the trial will continue until the value for `trial_duration` is reached. You can use this parameter to force the subject to view a stimulus for a fixed amount of time, even if they respond before the time is complete.
## Data Generated
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the stimulus first appears on the screen until the subject's response.
response | numeric | Indicates which button the subject pressed. The first button in the `choices` array is 0, the second is 1, and so on.
Note: the canvas stimulus is *not* included in the trial data because it is a function. Any stimulus information that should be saved in the trial data can be added via the `data` parameter.
## Examples
### Drawing circles based on parameters
```javascript
function filledCirc(canvas, radius, color){
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.arc(250, 250, radius, 0, 2 * Math.PI);
ctx.fillStyle = color;
ctx.fill()
}
var circle_1 = {
type: 'canvas-button-response',
stimulus: function (c) {
filledCirc(c, 100, 'blue');
},
choices: ['Red', 'Green', 'Blue'],
prompt: '<p>What color is the circle?</p>'
data: {color: 'blue', radius: 100}
};
var circle_2 = {
type: 'canvas-button-response',
stimulus: function (c) {
filledCirc(c, 150, 'green');
},
choices: ['Larger', 'Smaller'],
prompt: '<p>Is this circle larger or smaller than the last one?</p>',
data: {color: 'green', radius: 150}
};
```

View File

@ -0,0 +1,68 @@
# jspsych-canvas-keyboard-response
This plugin can be used to draw a stimulus on a [HTML canvas element](https://www.w3schools.com/html/html5_canvas.asp) and record a keyboard response. The canvas stimulus can be useful for displaying dynamic, parametrically-defined graphics, and for controlling the positioning of multiple graphical elements (shapes, text, images). The stimulus can be displayed until a response is given, or for a pre-determined amount of time. The trial can be ended automatically if the subject has failed to respond within a fixed length of time.
## Parameters
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
| Parameter | Type | Default Value | Description |
| ------------------- | ---------------- | ------------------ | ---------------------------------------- |
| stimulus | function | *undefined* | The function to draw on the canvas. This function automatically takes a canvas element as its only argument, e.g. `function(c) {...}` or `function drawStim(c) {...}`, where `c` refers to the canvas element. Note that the stimulus function will still generally need to set the correct context itself, using a line like `let ctx = c.getContext("2d")`. |
| canvas_size | array | [500, 500] | Array that defines the size of the canvas element in pixels. First value is height, second value is width. |
| choices | array of strings | `jsPsych.ALL_KEYS` | This array contains the key(s) that the subject is allowed to press in order to respond to the stimulus. Keys should be specified as characters (e.g., `'a'`, `'q'`, `' '`, `'Enter'`, `'ArrowDown'`) - see [this page](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values) and [this page (event.key column)](https://www.freecodecamp.org/news/javascript-keycode-list-keypress-event-key-codes/) for more examples. Any key presses that are not listed in the array will be ignored. The default value of `jsPsych.ALL_KEYS` means that all keys will be accepted as valid responses. Specifying `jsPsych.NO_KEYS` will mean that no responses are allowed. |
| prompt | string | null | This string can contain HTML markup. Any content here will be displayed below the stimulus. The intention is that it can be used to provide a reminder about the action the subject is supposed to take (e.g., which key to press). |
| stimulus_duration | numeric | null | How long to display the stimulus in milliseconds. The visibility CSS property of the stimulus will be set to `hidden` after this time has elapsed. If this is null, then the stimulus will remain visible until the trial ends. |
| trial_duration | numeric | null | How long to wait for the subject to make a response before ending the trial in milliseconds. If the subject fails to make a response before this timer is reached, the subject's response will be recorded as null for the trial and the trial will end. If the value of this parameter is null, then the trial will wait for a response indefinitely. |
| response_ends_trial | boolean | true | If true, then the trial will end whenever the subject makes a response (assuming they make their response before the cutoff specified by the `trial_duration` parameter). If false, then the trial will continue until the value for `trial_duration` is reached. You can use this parameter to force the subject to view a stimulus for a fixed amount of time, even if they respond before the time is complete. |
## Data Generated
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
| Name | Type | Value |
| --------- | ------- | ---------------------------------------- |
| response | string | Indicates which key the subject pressed. |
| rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the stimulus first appears on the screen until the subject's response. |
Note: the canvas stimulus is *not* included in the trial data because it is a function. Any stimulus information that should be saved in the trial data can be added via the `data` parameter.
## Examples
### Draw rectangle and wait for response
```javascript
function drawRect(c){
var ctx = c.getContext('2d');
ctx.beginPath();
ctx.rect(30, 30, 200, 50);
ctx.stroke();
}
var trial = {
type: 'canvas-keyboard-response',
stimulus: drawRect,
choices: ['e','i'],
prompt: '<p>Is this a circle or a rectangle? Press "e" for circle and "i" for rectangle.</p>',
data: {shape: 'rectangle'}
}
```
### Draw circle, no response allowed
```javascript
function drawCirc(c){
var ctx = c.getContext('2d');
ctx.beginPath();
ctx.arc(100, 75, 50, 0, 2 * Math.PI);
ctx.stroke();
}
var trial = {
type: 'canvas-keyboard-response',
stimulus: drawCirc,
choices: jsPsych.NO_KEYS,
trial_duration: 1000,
data: {shape: 'circle', radius: 50}
}
```

View File

@ -0,0 +1,89 @@
# jspsych-canvas-slider-response
This plugin can be used to draw a stimulus on a [HTML canvas element](https://www.w3schools.com/html/html5_canvas.asp) and collect a response within a range of values, which is made by dragging a slider. The canvas stimulus can be useful for displaying dynamic, parametrically-defined graphics, and for controlling the positioning of multiple graphical elements (shapes, text, images). The stimulus can be displayed until a response is given, or for a pre-determined amount of time. The trial can be ended automatically if the subject has failed to respond within a fixed length of time.
## Parameters
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
stimulus | function | *undefined* | The function to draw on the canvas. This function automatically takes a canvas element as its only argument, e.g. `function(c) {...}` or `function drawStim(c) {...}`, where `c` refers to the canvas element. Note that the stimulus function will still generally need to set the correct context itself, using a line like `let ctx = c.getContext("2d")`.
canvas_size | array | [500, 500] | Array that defines the size of the canvas element in pixels. First value is height, second value is width.
labels | array of strings | [] | Labels displayed at equidistant locations on the slider. For example, two labels will be placed at the ends of the slider. Three labels would place two at the ends and one in the middle. Four will place two at the ends, and the other two will be at 33% and 67% of the slider width.
button_label | string | 'Continue' | Label of the button to end the trial.
min | integer | 0 | Sets the minimum value of the slider.
max | integer | 100 | Sets the maximum value of the slider.
slider_start | integer | 50 | Sets the starting value of the slider.
step | integer | 1 | Sets the step of the slider. This is the smallest amount by which the slider can change.
slider_width | integer | null | Set the width of the slider in pixels. If left null, then the width will be equal to the widest element in the display.
require_movement | boolean | false | If true, the subject must click the slider before clicking the continue button.
prompt | string | null | This string can contain HTML markup. Any content here will be displayed below the stimulus. The intention is that it can be used to provide a reminder about the action the subject is supposed to take (e.g., what question to answer).
stimulus_duration | numeric | null | How long to display the stimulus in milliseconds. The visibility CSS property of the stimulus will be set to `hidden` after this time has elapsed. If this is null, then the stimulus will remain visible until the trial ends.
trial_duration | numeric | null | How long to wait for the subject to make a response before ending the trial in milliseconds. If the subject fails to make a response before this timer is reached, the subject's response will be recorded as null for the trial and the trial will end. If the value of this parameter is null, then the trial will wait for a response indefinitely.
response_ends_trial | boolean | true | If true, then the trial will end whenever the subject makes a response (assuming they make their response before the cutoff specified by the `trial_duration` parameter). If false, then the trial will continue until the value for `trial_duration` is reached. You can use this parameter to force the subject to view a stimulus for a fixed amount of time, even if they respond before the time is complete.
## Data Generated
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
response | numeric | The numeric value of the slider.
rt | numeric | The time in milliseconds for the subject to make a response. The time is measured from when the stimulus first appears on the screen until the subject's response.
Note: the canvas stimulus is *not* included in the trial data because it is a function. Any stimulus information that should be saved in the trial data can be added via the `data` parameter.
## Examples
### Draw two squares
```javascript
var colors = [#'FF3333', '#FF6A33'];
function twoSquares(c) {
var ctx = c.getContext('2d');
ctx.fillStyle = colors[0];
ctx.fillRect(200, 70, 40, 40);
ctx.fillStyle = colors[1];
ctx.fillRect(260, 70, 40, 40);
}
var trial = {
type: 'canvas-slider-response',
stimulus: twoSquares,
labels: ['0','10'],
canvas_size: [200, 500],
prompt: '<p>How different would you say the colors of these two squares are on a scale from 0 (the same) to 10 (completely different)</p>',
data: {color1: colors[0], color2: colors[1]}
}
```
### Draw two squares with additional parameters
```javascript
var colors;
function twoSquares(c, colors) {
var ctx = c.getContext('2d');
ctx.fillStyle = colors[0];
ctx.fillRect(200, 70, 40, 40);
ctx.fillStyle = colors[1];
ctx.fillRect(260, 70, 40, 40);
}
var trial = {
type: 'canvas-slider-response',
stimulus: function(c) {
colors = ['darkred', 'cyan'];
twoSquares(c, colors);
},
labels: ['Exactly<br>the same','Totally<br>different'],
canvas_size: [200, 500],
prompt: '<p>How different would you say the colors of these two squares are?</p>',
on_finish: function(data) {
data.color1 = colors[0];
data.color2 = colors[1];
}
};
```

View File

@ -4,32 +4,33 @@ The categorize animation plugin shows a sequence of images at a specified frame
## Parameters
Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
stimuli | array | *undefined* | Each element of the array is a path to an image file.
choices | array of keycodes | `jsPsych.ALL_KEYS` | This array contains the keys that the subject is allowed to press in order to respond to the stimulus. Keys can be specified as their [numeric key code](http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes) or as characters (e.g., `'a'`, `'q'`). The default value of `jsPsych.ALL_KEYS` means that all keys will be accepted as valid responses. Specifying `jsPsych.NO_KEYS` will mean that no responses are allowed.
key_answer | numeric | *undefined* | A [numeric key code](http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes) indicating the correct response.
text_answer | string | "" | A text label that describes the correct answer. Used in conjunction with the `correct_text` and `incorrect_text` parameters.
correct_text | string | "Correct." | String to show when the correct answer is given. Can contain HTML formatting. The special string `%ANS%` can be used within the string. If present, the plugin will put the `text_answer` for the trial in place of the %ANS% string (see example below).
incorrect_text | string | "Wrong." | String to show when the wrong answer is given. Can contain HTML formatting. The special string `%ANS%` can be used within the string. If present, the plugin will put the `text_answer` for the trial in place of the %ANS% string (see example below).
frame_time | numeric | 500 | How long to display each image (in milliseconds).
sequence_reps | numeric | 1 | How many times to show the entire sequence.
allow_response_before_complete | boolean | false | If true, the subject can respond before the animation sequence finishes.
prompt | string | null | This string can contain HTML markup. Any content here will be displayed below the stimulus. The intention is that it can be used to provide a reminder about the action the subject is supposed to take (e.g., which key to press).
feedback_duration | numeric | 2000 | How long to show the feedback (milliseconds).
| Parameter | Type | Default Value | Description |
| ------------------------------ | ---------------- | ------------------ | ---------------------------------------- |
| stimuli | array | *undefined* | Each element of the array is a path to an image file. |
| choices | array of strings | `jsPsych.ALL_KEYS` | This array contains the key(s) that the subject is allowed to press in order to respond to the stimulus. Keys should be specified as characters (e.g., `'a'`, `'q'`, `' '`, `'Enter'`, `'ArrowDown'`) - see [this page](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values) and [this page (event.key column)](https://www.freecodecamp.org/news/javascript-keycode-list-keypress-event-key-codes/) for more examples. Any key presses that are not listed in the array will be ignored. The default value of `jsPsych.ALL_KEYS` means that all keys will be accepted as valid responses. Specifying `jsPsych.NO_KEYS` will mean that no responses are allowed. |
| key_answer | string | *undefined* | The key character indicating the correct response. |
| text_answer | string | "" | A text label that describes the correct answer. Used in conjunction with the `correct_text` and `incorrect_text` parameters. |
| correct_text | string | "Correct." | String to show when the correct answer is given. Can contain HTML formatting. The special string `%ANS%` can be used within the string. If present, the plugin will put the `text_answer` for the trial in place of the %ANS% string (see example below). |
| incorrect_text | string | "Wrong." | String to show when the wrong answer is given. Can contain HTML formatting. The special string `%ANS%` can be used within the string. If present, the plugin will put the `text_answer` for the trial in place of the %ANS% string (see example below). |
| frame_time | numeric | 500 | How long to display each image (in milliseconds). |
| sequence_reps | numeric | 1 | How many times to show the entire sequence. |
| allow_response_before_complete | boolean | false | If true, the subject can respond before the animation sequence finishes. |
| prompt | string | null | This string can contain HTML markup. Any content here will be displayed below the stimulus. The intention is that it can be used to provide a reminder about the action the subject is supposed to take (e.g., which key to press). |
| feedback_duration | numeric | 2000 | How long to show the feedback (milliseconds). |
| render_on_canvas | boolean | true | If true, the images will be drawn onto a canvas element. This prevents a blank screen (white flash) between consecutive images in some browsers, like Firefox and Edge. If false, the image will be shown via an img element, as in previous versions of jsPsych. |
## Data Generated
In addition to the [default data collected by all plugins](overview#datacollectedbyplugins), this plugin collects the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
stimulus | JSON | JSON encoded representation of the array of stimuli displayed in the trial.
key_press | numeric | Indicates which key the subject pressed. The value is the [numeric key code](http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes) corresponding to the subject's response.
rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the stimulus first appears on the screen until the subject's response.
correct | boolean | `true` if the subject got the correct answer, `false` otherwise.
| Name | Type | Value |
| --------- | ------- | ---------------------------------------- |
| stimulus | array | Array of stimuli displayed in the trial. This will be encoded as a JSON string when data is saved using the `.json()` or `.csv()` functions. |
| response | string | Indicates which key the subject pressed. |
| rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the stimulus first appears on the screen until the subject's response. |
| correct | boolean | `true` if the subject got the correct answer, `false` otherwise. |
## Examples
@ -39,8 +40,8 @@ correct | boolean | `true` if the subject got the correct answer, `false` otherw
var animation_trial = {
type: 'categorize-animation',
stimuli: ["img/face_3.jpg", "img/face_2.jpg", "img/face_4.jpg", "img/face_1.jpg"],
choices: [80, 81], // 80 = 'p', 81 = 'q'
key_answer: 81, // correct answer is 'q' for both trials
choices: ['p', 'q'],
key_answer: 'q',
};
```
@ -50,8 +51,8 @@ var animation_trial = {
var animation_trial = {
type: 'categorize-animation',
stimuli: ["img/face_3.jpg", "img/face_2.jpg", "img/face_4.jpg", "img/face_1.jpg"],
choices: [80, 81], // 80 = 'p', 81 = 'q'
key_answer: 81, // correct answer is 'q' for both trials
choices: ['p', 'q'],
key_answer: 'q',
text_answer: 'Dax', // the label for the sequence is 'Dax'
correct_text: 'Correct! This was a %ANS%.',
incorrect_text: 'Incorrect. This was a %ANS%.'

View File

@ -4,35 +4,35 @@ The categorize html plugin shows an HTML object on the screen. The subject respo
## Parameters
Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
stimulus | html string | *undefined* | The HTML stimulus to display.
choices | array of keycodes | `jsPsych.ALL_KEYS` | This array contains the keys that the subject is allowed to press in order to respond to the stimulus. Keys can be specified as their [numeric key code](http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes) or as characters (e.g., `'a'`, `'q'`). The default value of `jsPsych.ALL_KEYS` means that all keys will be accepted as valid responses. Specifying `jsPsych.NO_KEYS` will mean that no responses are allowed.
key_answer | numeric | *undefined* | The [numeric key code](http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes) indicating the correct response.
text_answer | string | "" | A label that is associated with the correct answer. Used in conjunction with the `correct_text` and `incorrect_text` parameters.
correct_text | string | "Correct." | String to show when the correct answer is given. Can contain HTML formatting. The special string `%ANS%` can be used within the string. If present, the plugin will put the `text_answer` for the trial in place of the `%ANS%` string (see example below).
incorrect_text | string | "Wrong." | String to show when the wrong answer is given. Can contain HTML formatting. The special string `%ANS%` can be used within the string. If present, the plugin will put the `text_answer` for the trial in place of the `%ANS%` string (see example below).
prompt | string | null | This string can contain HTML markup. Any content here will be displayed below the stimulus. The intention is that it can be used to provide a reminder about the action the subject is supposed to take (e.g., which key to press).
force_correct_button_press | boolean | false | If set to true, then the subject must press the correct response key after feedback is given in order to advance to the next trial.
show_stim_with_feedback | boolean | true | If set to true, then the stimulus will be shown during feedback. If false, then only the text feedback will display during feedback.
show_feedback_on_timeout | boolean | false | If true, then category feedback will be displayed for an incorrect response after a timeout (timing_response is exceeded). If false, then a timeout message will be shown.
timeout_message | string | "Please respond faster." | The message to show on a timeout non-response.
stimulus_duration | numeric | null | How long to show the stimulus for (milliseconds). If null, then the stimulus is shown until a response is given.
feedback_duration | numeric | 2000 | How long to show the feedback for (milliseconds).
trial_duration | numeric | null | The maximum time allowed for a response. If null, then the experiment will wait indefinitely for a response.
| Parameter | Type | Default Value | Description |
| -------------------------- | ---------------- | ------------------------ | ---------------------------------------- |
| stimulus | html string | *undefined* | The HTML stimulus to display. |
| choices | array of strings | `jsPsych.ALL_KEYS` | This array contains the key(s) that the subject is allowed to press in order to respond to the stimulus. Keys should be specified as characters (e.g., `'a'`, `'q'`, `' '`, `'Enter'`, `'ArrowDown'`) - see [this page](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values) and [this page (event.key column)](https://www.freecodecamp.org/news/javascript-keycode-list-keypress-event-key-codes/) for more examples. Any key presses that are not listed in the array will be ignored. The default value of `jsPsych.ALL_KEYS` means that all keys will be accepted as valid responses. Specifying `jsPsych.NO_KEYS` will mean that no responses are allowed. |
| key_answer | string | *undefined* | The key character indicating the correct response. |
| text_answer | string | "" | A label that is associated with the correct answer. Used in conjunction with the `correct_text` and `incorrect_text` parameters. |
| correct_text | string | "Correct." | String to show when the correct answer is given. Can contain HTML formatting. The special string `%ANS%` can be used within the string. If present, the plugin will put the `text_answer` for the trial in place of the `%ANS%` string (see example below). |
| incorrect_text | string | "Wrong." | String to show when the wrong answer is given. Can contain HTML formatting. The special string `%ANS%` can be used within the string. If present, the plugin will put the `text_answer` for the trial in place of the `%ANS%` string (see example below). |
| prompt | string | null | This string can contain HTML markup. Any content here will be displayed below the stimulus. The intention is that it can be used to provide a reminder about the action the subject is supposed to take (e.g., which key to press). |
| force_correct_button_press | boolean | false | If set to true, then the subject must press the correct response key after feedback is given in order to advance to the next trial. |
| show_stim_with_feedback | boolean | true | If set to true, then the stimulus will be shown during feedback. If false, then only the text feedback will display during feedback. |
| show_feedback_on_timeout | boolean | false | If true, then category feedback will be displayed for an incorrect response after a timeout (trial_duration is exceeded). If false, then a timeout message will be shown. |
| timeout_message | string | "Please respond faster." | The message to show on a timeout non-response. |
| stimulus_duration | numeric | null | How long to show the stimulus for (milliseconds). If null, then the stimulus is shown until a response is given. |
| feedback_duration | numeric | 2000 | How long to show the feedback for (milliseconds). |
| trial_duration | numeric | null | The maximum time allowed for a response. If null, then the experiment will wait indefinitely for a response. |
## Data Generated
In addition to the [default data collected by all plugins](overview#datacollectedbyplugins), this plugin collects the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
stimulus | string | Either the path to the image file or the string containing the HTML formatted content that the subject saw on this trial.
key_press | numeric | Indicates which key the subject pressed. The value is the [numeric key code](http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes) corresponding to the subject's response.
rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the stimulus first appears on the screen until the subject's response.
correct | boolean | `true` if the subject got the correct answer, `false` otherwise.
| Name | Type | Value |
| --------- | ------- | ---------------------------------------- |
| stimulus | string | Either the path to the image file or the string containing the HTML formatted content that the subject saw on this trial. |
| response | string | Indicates which key the subject pressed. |
| rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the stimulus first appears on the screen until the subject's response. |
| correct | boolean | `true` if the subject got the correct answer, `false` otherwise. |
## Examples
@ -42,11 +42,12 @@ correct | boolean | `true` if the subject got the correct answer, `false` otherw
var categorization_trial = {
type: 'categorize',
stimulus: '<p>B</p>',
key_answer: 80,
key_answer: 'p',
text_answer: 'letter',
choices: [80, 81],
choices: ['p', 'q'],
correct_text: "<p class='prompt'>Correct, this is a %ANS%.</p>",
incorrect_text: "<p class='prompt'>Incorrect, this is a %ANS%.</p>",
prompt: "<p>Press P for letter. Press Q for number.</p>"
prompt: "<p>Press p for letter. Press q for number.</p>"
};
```

View File

@ -4,36 +4,36 @@ The categorize image plugin shows an image object on the screen. The subject res
## Parameters
Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
stimulus | string | *undefined* | The path to the image file.
key_answer | numeric | *undefined* | The [numeric key code](http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes) indicating the correct response.
choices | array of keycodes | `jsPsych.ALL_KEYS` | This array contains the keys that the subject is allowed to press in order to respond to the stimulus. Keys can be specified as their [numeric key code](http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes) or as characters (e.g., `'a'`, `'q'`). The default value of `jsPsych.ALL_KEYS` means that all keys will be accepted as valid responses. Specifying `jsPsych.NO_KEYS` will mean that no responses are allowed.
text_answer | string | "" | A label that is associated with the correct answer. Used in conjunction with the `correct_text` and `incorrect_text` parameters.
correct_text | string | "Correct." | String to show when the correct answer is given. Can contain HTML formatting. The special string `%ANS%` can be used within the string. If present, the plugin will put the `text_answer` for the trial in place of the %ANS% string (see example below).
incorrect_text | string | "Wrong." | String to show when the wrong answer is given. Can contain HTML formatting. The special string `%ANS%` can be used within the string. If present, the plugin will put the `text_answer` for the trial in place of the %ANS% string (see example below).
prompt | string | null | This string can contain HTML markup. Any content here will be displayed below the stimulus. The intention is that it can be used to provide a reminder about the action the subject is supposed to take (e.g., which key to press).
force_correct_button_press | boolean | false | If set to true, then the subject must press the correct response key after feedback is given in order to advance to the next trial.
show_stim_with_feedback | boolean | true | If set to true, then the stimulus will be shown during feedback. If false, then only the text feedback will display during feedback.
show_feedback_on_timeout | boolean | false | If true, then category feedback will be displayed for an incorrect response after a timeout (timing_response is exceeded). If false, then a timeout message will be shown.
timeout_message | string | "Please respond faster." | The message to show on a timeout non-response.
stimulus_duration | numeric | null | How long to show the stimulus for (milliseconds). If null, then the stimulus is shown until a response is given.
feedback_duration | numeric | 2000 | How long to show the feedback for (milliseconds).
trial_duration | numeric | null | The maximum time allowed for a response. If null, then the experiment will wait indefinitely for a response.
| Parameter | Type | Default Value | Description |
| -------------------------- | ---------------- | ------------------------ | ---------------------------------------- |
| stimulus | string | *undefined* | The path to the image file. |
| key_answer | string | *undefined* | The key character indicating the correct response. |
| choices | array of strings | `jsPsych.ALL_KEYS` | This array contains the key(s) that the subject is allowed to press in order to respond to the stimulus. Keys should be specified as characters (e.g., `'a'`, `'q'`, `' '`, `'Enter'`, `'ArrowDown'`) - see [this page](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values) and [this page (event.key column)](https://www.freecodecamp.org/news/javascript-keycode-list-keypress-event-key-codes/) for more examples. Any key presses that are not listed in the array will be ignored. The default value of `jsPsych.ALL_KEYS` means that all keys will be accepted as valid responses. Specifying `jsPsych.NO_KEYS` will mean that no responses are allowed. |
| text_answer | string | "" | A label that is associated with the correct answer. Used in conjunction with the `correct_text` and `incorrect_text` parameters. |
| correct_text | string | "Correct." | String to show when the correct answer is given. Can contain HTML formatting. The special string `%ANS%` can be used within the string. If present, the plugin will put the `text_answer` for the trial in place of the %ANS% string (see example below). |
| incorrect_text | string | "Wrong." | String to show when the wrong answer is given. Can contain HTML formatting. The special string `%ANS%` can be used within the string. If present, the plugin will put the `text_answer` for the trial in place of the %ANS% string (see example below). |
| prompt | string | null | This string can contain HTML markup. Any content here will be displayed below the stimulus. The intention is that it can be used to provide a reminder about the action the subject is supposed to take (e.g., which key to press). |
| force_correct_button_press | boolean | false | If set to true, then the subject must press the correct response key after feedback is given in order to advance to the next trial. |
| show_stim_with_feedback | boolean | true | If set to true, then the stimulus will be shown during feedback. If false, then only the text feedback will display during feedback. |
| show_feedback_on_timeout | boolean | false | If true, then category feedback will be displayed for an incorrect response after a timeout (trial_duration is exceeded). If false, then a timeout message will be shown. |
| timeout_message | string | "Please respond faster." | The message to show on a timeout non-response. |
| stimulus_duration | numeric | null | How long to show the stimulus for (milliseconds). If null, then the stimulus is shown until a response is given. |
| feedback_duration | numeric | 2000 | How long to show the feedback for (milliseconds). |
| trial_duration | numeric | null | The maximum time allowed for a response. If null, then the experiment will wait indefinitely for a response. |
## Data Generated
In addition to the [default data collected by all plugins](overview#datacollectedbyplugins), this plugin collects the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
stimulus | string | Either the path to the image file or the string containing the HTML formatted content that the subject saw on this trial.
key_press | numeric | Indicates which key the subject pressed. The value is the [numeric key code](http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes) corresponding to the subject's response.
rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the stimulus first appears on the screen until the subject's response.
correct | boolean | `true` if the subject got the correct answer, `false` otherwise.
| Name | Type | Value |
| --------- | ------- | ---------------------------------------- |
| stimulus | string | Either the path to the image file or the string containing the HTML formatted content that the subject saw on this trial. |
| response | string | Indicates which key the subject pressed. |
| rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the stimulus first appears on the screen until the subject's response. |
| correct | boolean | `true` if the subject got the correct answer, `false` otherwise. |
## Examples
@ -43,9 +43,9 @@ correct | boolean | `true` if the subject got the correct answer, `false` otherw
var categorization_trial = {
type: 'categorize-image',
stimulus: 'img/harrypotter.png',
key_answer: 71,
key_answer: 'g',
text_answer: 'Gryffindor',
choices: [71, 72, 82, 83],
choices: ['g', 'h', 'r', 's'],
correct_text: "<p class='prompt'>Correct! This person is a %ANS%.</p>",
incorrect_text: "<p class='prompt'>Incorrect. This person is a %ANS%.</p>",
prompt: "<p>Is this person a (G)ryffindor, (H)ufflepuff, (R)avenclaw, or (S)lytherin?</p>"

View File

@ -1,23 +1,25 @@
# jspsych-cloze
# *jspsych-cloze
This plugin displays a text with certain words removed. Participants are asked to replace the missing items. Responses are recorded when clicking a button. Optionally, responses are evaluated and a function is called in case of differences, making it possible to inform participants about mistakes.
## Parameters
Parameter | Type | Default Value | Description
----------|------|---------------|------------
text | string | undefined | The cloze text to be displayed. Blanks are indicated by %% signs and automatically replaced by input fields. If there is a correct answer you want the system to check against, it must be typed between the two percentage signs (i.e. % correct solution %).
button_text | string | OK | Text of the button participants have to press for finishing the cloze test.
check_answers | boolean | false | Boolean value indicating if the answers given by participants should be compared against a correct solution given in the text (between % signs) after the button was clicked. If ```true```, answers are checked and in case of differences, the ```mistake_fn``` is called. In this case, the trial does not automatically finish. If ```false```, no checks are performed and the trial automatically ends when clicking the button.
mistake_fn | function | ```function(){}``` | Function called if ```check_answers``` is set to ```true``` and there is a difference between the participants answers and the correct solution provided in the text.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
| Parameter | Type | Default Value | Description |
| ------------- | -------- | ------------------ | ---------------------------------------- |
| text | string | *undefined* | The cloze text to be displayed. Blanks are indicated by %% signs and automatically replaced by input fields. If there is a correct answer you want the system to check against, it must be typed between the two percentage signs (i.e. % correct solution %). |
| button_text | string | OK | Text of the button participants have to press for finishing the cloze test. |
| check_answers | boolean | false | Boolean value indicating if the answers given by participants should be compared against a correct solution given in the text (between % signs) after the button was clicked. If ```true```, answers are checked and in case of differences, the ```mistake_fn``` is called. In this case, the trial does not automatically finish. If ```false```, no checks are performed and the trial automatically ends when clicking the button. |
| mistake_fn | function | ```function(){}``` | Function called if ```check_answers``` is set to ```true``` and there is a difference between the participants answers and the correct solution provided in the text. |
## Data Generated
In addition to the [default data collected by all plugins](overview#datacollectedbyplugins), this plugin collects the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
answers | array of strings | Answers the partcipant gave
| Name | Type | Value |
| -------- | ---------------- | --------------------------- |
| response | array of strings | Answers the partcipant gave |
## Examples

View File

@ -4,25 +4,25 @@ The HTML plugin displays an external HTML document (often a consent form). Eithe
## Parameters
Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
url | string | *undefined* | The URL of the page to display.
cont_key | numeric | null | The key code a key to advance to the next trial. If left as null, then the subject will not be able to advance trials using the keyboard.
cont_btn | string | null | The ID of a clickable element on the page. When the element is clicked, the trial will advance.
check_fn | function | `function(){ return true; }` | This function is called with the jsPsych `display_element` as the only argument when the subject attempts to advance the trial. The trial will only advance if the function return `true`. This can be used to verify that the subject has correctly filled out a form before continuing, for example.
force_refresh | boolean | false | If `true`, then the plugin will avoid using the cached version of the HTML page to load if one exists.
execute_script | boolean | false | If `true`, then scripts on the remote page will be executed.
| Parameter | Type | Default Value | Description |
| -------------- | -------- | ---------------------------- | ---------------------------------------- |
| url | string | *undefined* | The URL of the page to display. |
| cont_key | string | null | The key character the subject can use to advance to the next trial. If left as null, then the subject will not be able to advance trials using the keyboard. |
| cont_btn | string | null | The ID of a clickable element on the page. When the element is clicked, the trial will advance. |
| check_fn | function | `function(){ return true; }` | This function is called with the jsPsych `display_element` as the only argument when the subject attempts to advance the trial. The trial will only advance if the function return `true`. This can be used to verify that the subject has correctly filled out a form before continuing, for example. |
| force_refresh | boolean | false | If `true`, then the plugin will avoid using the cached version of the HTML page to load if one exists. |
| execute_script | boolean | false | If `true`, then scripts on the remote page will be executed. |
## Data Generated
In addition to the [default data collected by all plugins](overview#datacollectedbyplugins), this plugin collects the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
url | string | The URL of the page.
rt | numeric | The response time in milliseconds for the subject to finish the trial.
| Name | Type | Value |
| ---- | ------- | ---------------------------------------- |
| url | string | The URL of the page. |
| rt | numeric | The response time in milliseconds for the subject to finish the trial. |
## Examples

View File

@ -1,37 +1,41 @@
# jspsych-free-sort plugin
The free-sort plugin displays a collection of images on the screen that the subject can interact with by clicking and dragging. All of the moves that the subject performs are recorded.
## Dependency
This plugin requires the jQuery UI library, available at [https://jqueryui.com/](https://jqueryui.com/). You must include the library in the `<head>` section of your experiment page. You can use the [Google-hosted version of the library](https://developers.google.com/speed/libraries/#jquery-ui).
The free-sort plugin displays one or more images on the screen that the participant can interact with by clicking and dragging. When the trial starts, the images can be positioned outside or inside the sort area. All images must be moved into the sorting area before the participant can click a button to end the trial. All of the moves that the participant performs are recorded, as well as the final positions of all images. This plugin could be useful when asking participants to position images based on similarity to one another, or to recall image spatial locations.
## Parameters
Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
stimuli | array | *undefined* | Each element of this array is an image path.
stim_height | numeric | 100 | The height of the images in pixels.
stim_width | numeric | 100 | The width of the images in pixels.
sort_area_height | numeric | 800 | The height of the container that subjects can move the stimuli in. Stimuli will be constrained to this area.
sort_area_width | numeric | 800 | The width of the container that subjects can move the stimuli in. Stimuli will be constrained to this area.
prompt | string | null | This string can contain HTML markup. The intention is that it can be used to provide a reminder about the action the subject is supposed to take (e.g., which key to press).
scale_factor | numeric | 1.5 | How much larger to make the stimulus while moving (1 = no scaling).
sort_area_height | numeric | 800 | The height of the container that participants can move the stimuli in. Stimuli will be constrained to this area.
sort_area_width | numeric | 800 | The width of the container that participants can move the stimuli in. Stimuli will be constrained to this area.
sort_area_shape | string | "ellipse" | The shape of the sorting area, can be "ellipse" or "square".
prompt | string | null | This string can contain HTML markup. The intention is that it can be used to provide a reminder about the action the participant is supposed to take (e.g., which key to press).
prompt_location | string | "above" | Indicates whether to show the prompt `"above"` or `"below"` the sorting area.
button_label | string | 'Continue' | The text that appears on the button to continue to the next trial.
button_label | string | 'Continue' | The text that appears on the button to continue to the next trial.
change_border_background_color | boolean | true | If `true`, the sort area border color will change while items are being moved in and out of the sort area, and the background color will change once all items have been moved into the sort area. If `false`, the border will remain black and the background will remain white throughout the trial.
border_color_in | string | '#a1d99b' | If `change_border_background_color` is `true`, the sort area border will change to this color when an item is being moved into the sort area, and the background will change to this color when all of the items have been moved into the sort area.
border_color_out | string | '#fc9272' | If `change_border_background_color` is `true`, this will be the color of the sort area border when there are one or more items that still need to be moved into the sort area.
border_width | numeric | null | The width in pixels of the border around the sort area. If `null`, the border width will be 3% of the `sort_area_height`.
counter_text_unfinished | string | You still need to place %n% item%s% inside the sort area. | Text to display when there are one or more items that still need to be placed in the sort area. If "%n%" is included in the string, it will be replaced with the number of items that still need to be moved inside. If "%s%" is included in the string, a "s" will be included when the number of items remaining is greater than one.
counter_text_finished | string | All items placed. Feel free to reposition items if necessary. | Text that will take the place of the counter_text_unfinished text when all items have been moved inside the sort area.
stim_starts_inside | boolean | false | If `false`, the images will be positioned to the left and right of the sort area when the trial loads. If `true`, the images will be positioned at random locations inside the sort area when the trial loads.
## Data Generated
In addition to the [default data collected by all plugins](overview#datacollectedbyplugins), this plugin collects the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
init_locations | JSON string | A JSON-encoded object representing the initial locations of all the stimuli in the sorting area. The object is an array with one element per stimulus. Each element in the array has a "src", "x", and "y" value. "src" is the image path, and "x" and "y" are the object location.
moves | JSON string | A JSON-encoded object representing all of the moves the participant made when sorting. The object is an array with each element representing a move. Each element in the array has a "src", "x", and "y" value. "src" is the image path, and "x" and "y" are the object location after the move.
final_locations | JSON string | A JSON-encoded object representing the final locations of all the stimuli in the sorting area. The object is an array with one element per stimulus. Each element in the array has a "src", "x", and "y" value. "src" is the image path, and "x" and "y" are the object location.
rt | numeric | The response time in milliseconds for the subject to finish all sorting.
init_locations | array | An array containing objects representing the initial locations of all the stimuli in the sorting area. Each element in the array represents a stimulus, and has a "src", "x", and "y" value. "src" is the image path, and "x" and "y" are the object location. This will be encoded as a JSON string when data is saved using the `.json()` or `.csv()` functions.
moves | array | An array containing objects representing all of the moves the participant made when sorting. Each object represents a move. Each element in the array has a "src", "x", and "y" value. "src" is the image path, and "x" and "y" are the object location after the move. This will be encoded as a JSON string when data is saved using the `.json()` or `.csv()` functions.
final_locations | array | An array containing objects representing the final locations of all the stimuli in the sorting area. Each element in the array represents a stimulus, and has a "src", "x", and "y" value. "src" is the image path, and "x" and "y" are the object location. This will be encoded as a JSON string when data is saved using the `.json()` or `.csv()` functions.
rt | numeric | The response time in milliseconds for the participant to finish all sorting.
## Examples

View File

@ -6,7 +6,7 @@ Safari does not support keyboard input when the browser is in fullscreen mode. T
## Parameters
Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
@ -17,7 +17,7 @@ delay_after | numeric | 1000 | The length of time to delay after entering fullsc
## Data Generated
In addition to the [default data collected by all plugins](overview#datacollectedbyplugins), this plugin collects the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------

View File

@ -4,8 +4,7 @@ This plugin displays HTML content and records responses generated by button clic
## Parameters
Parameters with a default value of *undefined* must be specified.
Other parameters can be left unspecified if the default value is acceptable.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
@ -17,16 +16,16 @@ trial_duration | numeric | null | How long to wait for the subject to make a res
stimulus_duration | numeric | null | How long to display the stimulus in milliseconds. The visibility CSS property of the stimulus will be set to `hidden` after this time has elapsed. If this is null, then the stimulus will remain visible until the trial ends.
margin_vertical | string | '0px' | Vertical margin of the button(s).
margin_horizontal | string | '8px' | Horizontal margin of the button(s).
response_ends_trial | boolean | true | If true, then the trial will end whenever the subject makes a response (assuming they make their response before the cutoff specified by the `trial_duration` parameter). If false, then the trial will continue until the value for `timing_response` is reached. You can use this parameter to force the subject to view a stimulus for a fixed amount of time, even if they respond before the time is complete.
response_ends_trial | boolean | true | If true, then the trial will end whenever the subject makes a response (assuming they make their response before the cutoff specified by the `trial_duration` parameter). If false, then the trial will continue until the value for `trial_duration` is reached. You can set this parameter to `false` to force the subject to view a stimulus for a fixed amount of time, even if they respond before the time is complete.
## Data Generated
In addition to the [default data collected by all plugins](overview#datacollectedbyplugins), this plugin collects the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the stimulus first appears on the screen until the subject's response.
button_pressed | numeric | Indicates which button the subject pressed. The first button in the `choices` array is 0, the second is 1, and so on.
response | numeric | Indicates which button the subject pressed. The first button in the `choices` array is 0, the second is 1, and so on.
stimulus | string | The HTML content that was displayed on the screen.
## Examples

View File

@ -5,26 +5,26 @@ This plugin displays HTML content and records responses generated with the keybo
## Parameters
Parameters with a default value of undefined must be specified. Other parameters can be left unspecified if the default value is acceptable.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of undefined must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
stimulus | HTML string | *undefined* | The string to be displayed.
choices | array of keycodes | `jsPsych.ALL_KEYS` | This array contains the keys that the subject is allowed to press in order to respond to the stimulus. Keys can be specified as their [numeric key code](http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes) or as characters (e.g., `'a'`, `'q'`). The default value of `jsPsych.ALL_KEYS` means that all keys will be accepted as valid responses. Specifying `jsPsych.NO_KEYS` will mean that no responses are allowed.
prompt | string | null | This string can contain HTML markup. Any content here will be displayed below the stimulus. The intention is that it can be used to provide a reminder about the action the subject is supposed to take (e.g., which key to press).
stimulus_duration | numeric | null | How long to display the stimulus in milliseconds. The visibility CSS property of the stimulus will be set to `hidden` after this time has elapsed. If this is null, then the stimulus will remain visible until the trial ends.
trial_duration | numeric | null | How long to wait for the subject to make a response before ending the trial in milliseconds. If the subject fails to make a response before this timer is reached, the subject's response will be recorded as null for the trial and the trial will end. If the value of this parameter is null, then the trial will wait for a response indefinitely.
response_ends_trial | boolean | true | If true, then the trial will end whenever the subject makes a response (assuming they make their response before the cutoff specified by the `timing_response` parameter). If false, then the trial will continue until the value for `trial_duration` is reached. You can use this parameter to force the subject to view a stimulus for a fixed amount of time, even if they respond before the time is complete.
| Parameter | Type | Default Value | Description |
| ------------------- | ---------------- | ------------------ | ---------------------------------------- |
| stimulus | HTML string | *undefined* | The string to be displayed. |
| choices | array of strings | `jsPsych.ALL_KEYS` | This array contains the key(s) that the subject is allowed to press in order to respond to the stimulus. Keys should be specified as characters (e.g., `'a'`, `'q'`, `' '`, `'Enter'`, `'ArrowDown'`) - see [this page](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values) and [this page (event.key column)](https://www.freecodecamp.org/news/javascript-keycode-list-keypress-event-key-codes/) for more examples. Any key presses that are not listed in the array will be ignored. The default value of `jsPsych.ALL_KEYS` means that all keys will be accepted as valid responses. Specifying `jsPsych.NO_KEYS` will mean that no responses are allowed. |
| prompt | string | null | This string can contain HTML markup. Any content here will be displayed below the stimulus. The intention is that it can be used to provide a reminder about the action the subject is supposed to take (e.g., which key to press). |
| stimulus_duration | numeric | null | How long to display the stimulus in milliseconds. The visibility CSS property of the stimulus will be set to `hidden` after this time has elapsed. If this is null, then the stimulus will remain visible until the trial ends. |
| trial_duration | numeric | null | How long to wait for the subject to make a response before ending the trial in milliseconds. If the subject fails to make a response before this timer is reached, the subject's response will be recorded as null for the trial and the trial will end. If the value of this parameter is null, then the trial will wait for a response indefinitely. |
| response_ends_trial | boolean | true | If true, then the trial will end whenever the subject makes a response (assuming they make their response before the cutoff specified by the `trial_duration` parameter). If false, then the trial will continue until the value for `trial_duration` is reached. You can set this parameter to `false` to force the subject to view a stimulus for a fixed amount of time, even if they respond before the time is complete. |
## Data Generated
In addition to the [default data collected by all plugins](overview#datacollectedbyplugins), this plugin collects the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
key_press | numeric | Indicates which key the subject pressed. The value is the [numeric key code](http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes) corresponding to the subject's response.
rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the stimulus first appears on the screen until the subject's response.
stimulus | string | The HTML content that was displayed on the screen.
| Name | Type | Value |
| --------- | ------- | ---------------------------------------- |
| response | string | Indicates which key the subject pressed. |
| rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the stimulus first appears on the screen until the subject's response. |
| stimulus | string | The HTML content that was displayed on the screen. |
## Examples

View File

@ -4,7 +4,7 @@ This plugin displays HTML content and allows the subject to respond by dragging
## Parameters
Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
@ -13,24 +13,25 @@ labels | array of strings | [] | Labels displayed at equidistant locations on th
button_label | string | 'Continue' | Label of the button to end the trial.
min | integer | 0 | Sets the minimum value of the slider.
max | integer | 100 | Sets the maximum value of the slider.
start | integer | 50 | Sets the starting value of the slider
slider_start | integer | 50 | Sets the starting value of the slider
step | integer | 1 | Sets the step of the slider. This is the smallest amount by which the slider can change.
slider_width | integer | null | Set the width of the slider in pixels. If left null, then the width will be equal to the widest element in the display.
require_movement | boolean | false | If true, the subject must move the slider before clicking the continue button.
prompt | string | null | This string can contain HTML markup. Any content here will be displayed below the stimulus. The intention is that it can be used to provide a reminder about the action the subject is supposed to take (e.g., which key to press).
stimulus_duration | numeric | null | How long to display the stimulus in milliseconds. The visibility CSS property of the stimulus will be set to `hidden` after this time has elapsed. If this is null, then the stimulus will remain visible until the trial ends.
trial_duration | numeric | null | How long to wait for the subject to make a response before ending the trial in milliseconds. If the subject fails to make a response before this timer is reached, the subject's response will be recorded as null for the trial and the trial will end. If the value of this parameter is null, then the trial will wait for a response indefinitely.
response_ends_trial | boolean | true | If true, then the trial will end whenever the subject makes a response (assuming they make their response before the cutoff specified by the `timing_response` parameter). If false, then the trial will continue until the value for `trial_duration` is reached. You can use this parameter to force the subject to view a stimulus for a fixed amount of time, even if they respond before the time is complete.
response_ends_trial | boolean | true | If true, then the trial will end whenever the subject makes a response (assuming they make their response before the cutoff specified by the `trial_duration` parameter). If false, then the trial will continue until the value for `trial_duration` is reached. You can set this parameter to `false` to force the subject to view a stimulus for a fixed amount of time, even if they respond before the time is complete.
## Data Generated
In addition to the [default data collected by all plugins](overview#datacollectedbyplugins), this plugin collects the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
response | numeric | The numeric value of the slider.
rt | numeric | The time in milliseconds for the subject to make a response. The time is measured from when the stimulus first appears on the screen until the subject's response.
stimulus | string | The HTML content that was displayed on the screen.
slider_start | numeric | The starting value of the slider.
## Examples

View File

@ -4,34 +4,34 @@ This plugin runs a single trial of the [implicit association test (IAT)](https:/
## Parameters
Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
stimulus | string | *undefined* | The HTML-format stimulus to display.
html_when_wrong | string | `<span style="color: red; font-size: 80px">X</span>` | The content to display when a user presses the wrong key.
bottom_instructions | string | `<p>If you press the wrong key, a red X will appear. Press any key to continue.</p>` | Instructions about making a wrong key press and whether another key press is needed to continue.
force_correct_key_press | boolean | false | If this is true and the user presses the wrong key then they have to press the other key to continue. An example would be two keys 'E' and 'I'. If the key associated with the stimulus is 'E' and key 'I' was pressed, then pressing 'E' is needed to continue the trial. When this is true, then parameter key_to_move_forward is not used.
display_feedback | boolean | false | If true, then `html_when_wrong` and `wrong_image_name` is required. If false, timing_response is needed and trial will continue automatically.
left_category_key | string | 'E' | Key press that is associated with the left_category_label.
right_category_key | string | 'I' | Key press that is associated with the right_category_label.
left_category_label | string | ['left'] | An array that contains the words/labels associated with a certain stimulus. The labels are aligned to the left side of the page.
right_category_label | string | ['right'] | An array that contains the words/labels associated with a certain stimulus. The labels are aligned to the right side of the page.
stim_key_association | string | 'undefined' | Inputs are either 'left' or 'right'. It will associate the stimulus with the key presses on the left or right side of the page(left_category_key or right_category_key).
key_to_move_forward | array of characters | [jsPsych.ALL_KEYS] | This array contains the characters the subject is allowed to press to move on to the next trial if their key press was incorrect and feedback was displayed. Can also have 'other key' as an option which will only allow the user to select the right key to move forward.
timing_response | numeric | null | How long to wait for the subject to make a response before ending the trial in milliseconds. If the subject fails to make a response before this timer is reached, the subject's response will be recorded as null for the trial and the trial will end. If the value of this parameter is null, then the trial will wait for a response indefinitely.
response_ends_trial | boolean | true | If true, then the trial will end whenever the subject makes a response (assuming they make their response before the cutoff specified by the `timing_response` parameter). If false, then the trial will continue until the value for `timing_response` is reached. You can use this parameter to force the subject to view a stimulus for a fixed amount of time, even if they respond before the time is complete.
| Parameter | Type | Default Value | Description |
| ----------------------- | ---------------- | ---------------------------------------- | ---------------------------------------- |
| stimulus | string | *undefined* | The HTML-formatted stimulus to display. |
| html_when_wrong | string | `<span style="color: red; font-size: 80px">X</span>` | The content to display when a user presses the wrong key. |
| bottom_instructions | string | `<p>If you press the wrong key, a red X will appear. Press any key to continue.</p>` | Instructions about making a wrong key press and whether another key press is needed to continue. |
| force_correct_key_press | boolean | false | If this is `true` and the user presses the wrong key then they have to press the other key to continue. An example would be two keys 'e' and 'i'. If the key associated with the stimulus is 'e' and key 'i' was pressed, then pressing 'e' is needed to continue the trial. When this is `true`, then parameter `key_to_move_forward` is not used. |
| display_feedback | boolean | false | If `true`, then `html_when_wrong` and `wrong_image_name` is required. If `false`, `trial_duration` is needed and trial will continue automatically. |
| left_category_key | string | 'e' | Key press that is associated with the `left_category_label`. |
| right_category_key | string | 'i' | Key press that is associated with the `right_category_label`. |
| left_category_label | string | ['left'] | An array that contains the words/labels associated with a certain stimulus. The labels are aligned to the left side of the page. |
| right_category_label | string | ['right'] | An array that contains the words/labels associated with a certain stimulus. The labels are aligned to the right side of the page. |
| stim_key_association | string | *undefined* | Either 'left' or 'right'. This indicates whether the stimulus is associated with the key press and category on the left or right side of the page (`left_category_key` or `right_category_key`). |
| key_to_move_forward | array of strings | jsPsych.ALL_KEYS | This array contains the characters the subject is allowed to press to move on to the next trial if their key press was incorrect and feedback was displayed. Can also have 'other key' as an option which will only allow the user to select the right key to move forward. |
| trial_duration | numeric | null | How long to wait for the subject to make a response before ending the trial in milliseconds. If the subject fails to make a response before this timer is reached, the subject's response will be recorded as `null` for the trial and the trial will end. If the value of this parameter is `null`, then the trial will wait for a response indefinitely. |
| response_ends_trial | boolean | true | If true, then the trial will end whenever the subject makes a response (assuming they make their response before the cutoff specified by the `trial_duration` parameter). If false, then the trial will continue until the value for `trial_duration` is reached. You can use this parameter to force the subject to view a stimulus for a fixed amount of time, even if they respond before the time is complete. |
## Data Generated
In addition to the [default data collected by all plugins](overview#datacollectedbyplugins), this plugin collects the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
stimulus | string | Either the path to the image file or the string containing the HTML formatted content that the subject saw on this trial.
key_press | numeric | Indicates which key the subject pressed. The value is the [numeric key code](http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes) corresponding to the subject's response.
rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the stimulus first appears on the screen until the subject's response.
correct | boolean | boolean of whether the user's key press was correct for the given image or incorrect.
| Name | Type | Value |
| --------- | ------- | ---------------------------------------- |
| stimulus | string | Either the path to the image file or the string containing the HTML-formatted content that the subject saw on this trial. |
| response | string | Indicates which key the subject pressed. |
| rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the stimulus first appears on the screen until the subject's response. |
| correct | boolean | Boolean indicating whether the user's key press was correct or incorrect for the given stimulus. |
## Examples
@ -44,9 +44,9 @@ var trial_block = {
bottom_instructions: '<p>If you press the wrong key, a red X will appear. Press the other key to continue</p>',
force_correct_key_press: true,
display_feedback: true,
timing_response: 3000, //Only if display_feedback is false
left_category_key: 'E',
right_category_key: 'I',
trial_duration: 3000, //Only if display_feedback is false
left_category_key: 'e',
right_category_key: 'i',
left_category_label: ['OLD'],
right_category_label: ['YOUNG'],
response_ends_trial: true

View File

@ -1,37 +1,37 @@
# jspsych-iat-image plugin
jspsych-iat-image plugin
This plugin runs a single trial of the [implicit association test (IAT)](https://implicit.harvard.edu/implicit/iatdetails.html), using an image as the stimulus.
## Parameters
Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
stimulus | string | *undefined* | The stimulus to display. The path to an image.
htm_when_wrong | string | `<span style="color: red; font-size: 80px">X</span>` | The image to display when a user presses the wrong key.
bottom_instructions | string | `<p>If you press the wrong key, a red X will appear. Press any key to continue.</p>` | Instructions about making a wrong key press and whether another key press is needed to continue.
force_correct_key_press | boolean | false | If this is true and the user presses the wrong key then they have to press the other key to continue. An example would be two keys 'E' and 'I'. If the key associated with the stimulus is 'E' and key 'I' was pressed, then pressing 'E' is needed to continue the trial. When this is true, then parameter key_to_move_forward is not used.
display_feedback | boolean | false | If true, then image_when_wrong and wrong_image_name is required. If false, timing_response is needed and trial will continue automatically.
left_category_key | string | 'E' | Key press that is associated with the left_category_label.
right_category_key | string | 'I' | Key press that is associated with the right_category_label.
left_category_label | string | ['left'] | An array that contains the words/labels associated with a certain stimulus. The labels are aligned to the left side of the page.
right_category_label | string | ['right'] | An array that contains the words/labels associated with a certain stimulus. The labels are aligned to the right side of the page.
stim_key_association | string | 'undefined' | Inputs are either 'left' or 'right'. It will associate the stimulus with the key presses on the left or right side of the page(left_category_key or right_category_key).
key_to_move_forward | array of characters | [jsPsych.ALL_KEYS] | This array contains the characters the subject is allowed to press to move on to the next trial if their key press was incorrect and feedback was displayed. Can also have 'other key' as an option which will only allow the user to select the right key to move forward.
timing_response | numeric | null | How long to wait for the subject to make a response before ending the trial in milliseconds. If the subject fails to make a response before this timer is reached, the subject's response will be recorded as null for the trial and the trial will end. If the value of this parameter is null, then the trial will wait for a response indefinitely.
response_ends_trial | boolean | true | If true, then the trial will end whenever the subject makes a response (assuming they make their response before the cutoff specified by the `timing_response` parameter). If false, then the trial will continue until the value for `timing_response` is reached. You can use this parameter to force the subject to view a stimulus for a fixed amount of time, even if they respond before the time is complete.
| Parameter | Type | Default Value | Description |
| ----------------------- | ------------------- | ---------------------------------------- | ---------------------------------------- |
| stimulus | string | *undefined* | The stimulus to display. The path to an image. |
| html_when_wrong | string | `<span style="color: red; font-size: 80px">X</span>` | The HTML to display when a user presses the wrong key. |
| bottom_instructions | string | `<p>If you press the wrong key, a red X will appear. Press any key to continue.</p>` | Instructions about making a wrong key press and whether another key press is needed to continue. |
| force_correct_key_press | boolean | false | If this is `true` and the user presses the wrong key then they have to press the other key to continue. An example would be two keys 'e' and 'i'. If the key associated with the stimulus is 'e' and key 'i' was pressed, then pressing 'e' is needed to continue the trial. When this is `true`, then parameter `key_to_move_forward` is not used. |
| display_feedback | boolean | false | If `true`, then `image_when_wrong` and `wrong_image_name` are required. If `false`, `trial_duration` is needed and trial will continue automatically. |
| left_category_key | string | 'e' | Key press that is associated with the `left_category_label`. |
| right_category_key | string | 'i' | Key press that is associated with the `right_category_label`. |
| left_category_label | string | ['left'] | An array that contains the words/labels associated with a certain stimulus. The labels are aligned to the left side of the page. |
| right_category_label | string | ['right'] | An array that contains the words/labels associated with a certain stimulus. The labels are aligned to the right side of the page. |
| stim_key_association | string | 'undefined' | Either 'left' or 'right'. This indicates whether the stimulus is associated with the key press and category on the left or right side of the page (`left_category_key` or `right_category_key`). |
| key_to_move_forward | array of characters | jsPsych.ALL_KEYS | This array contains the characters the subject is allowed to press to move on to the next trial if their key press was incorrect and feedback was displayed. Can also have 'other key' as an option which will only allow the user to select the right key to move forward. |
| trial_duration | numeric | null | How long to wait for the subject to make a response before ending the trial in milliseconds. If the subject fails to make a response before this timer is reached, the subject's response will be recorded as `null` for the trial and the trial will end. If the value of this parameter is `null`, then the trial will wait for a response indefinitely. |
| response_ends_trial | boolean | true | If true, then the trial will end whenever the subject makes a response (assuming they make their response before the cutoff specified by the `trial_duration` parameter). If false, then the trial will continue until the value for `trial_duration` is reached. You can use this parameter to force the subject to view a stimulus for a fixed amount of time, even if they respond before the time is complete. |
## Data Generated
In addition to the [default data collected by all plugins](overview#datacollectedbyplugins), this plugin collects the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
stimulus | string | Either the path to the image file or the string containing the HTML formatted content that the subject saw on this trial.
key_press | numeric | Indicates which key the subject pressed. The value is the [numeric key code](http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes) corresponding to the subject's response.
rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the stimulus first appears on the screen until the subject's response.
correct | boolean | boolean of whether the user's key press was correct for the given image or incorrect.
| Name | Type | Value |
| --------- | ------- | ---------------------------------------- |
| stimulus | string | Either the path to the image file or the string containing the HTML-formatted content that the subject saw on this trial. |
| response | string | Indicates which key the subject pressed. |
| rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the stimulus first appears on the screen until the subject's response. |
| correct | boolean | Boolean indicating whether the user's key press was correct or incorrect for the given image. |
## Examples
@ -44,9 +44,9 @@ var trial_block = {
bottom_instructions: '<p>If you press the wrong key, a red X will appear. Press the other key to continue</p>',
force_correct_key_press: true,
display_feedback: true,
timing_response: 3000, //Only if display_feedback is false
left_category_key: 'E',
right_category_key: 'I',
trial_duration: 3000, //Only if display_feedback is false
left_category_key: 'e',
right_category_key: 'i',
left_category_label: ['OLD'],
right_category_label: ['YOUNG'],
response_ends_trial: true

View File

@ -2,10 +2,11 @@
This plugin displays an image and records responses generated with a button click. The stimulus can be displayed until a response is given, or for a pre-determined amount of time. The trial can be ended automatically if the subject has failed to respond within a fixed length of time. The button itself can be customized using HTML formatting.
Image files can be automatically preloaded by jsPsych using the [`preload` plugin](jspsych-preload.md). However, if you are using timeline variables or another dynamic method to specify the image stimulus, you will need to [manually preload](/overview/media-preloading/#manual-preloading) the images.
## Parameters
Parameters with a default value of *undefined* must be specified.
Other parameters can be left unspecified if the default value is acceptable.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
@ -20,16 +21,17 @@ stimulus_duration | numeric | null | How long to show the stimulus for in millis
trial_duration | numeric | null | How long to wait for the subject to make a response before ending the trial in milliseconds. If the subject fails to make a response before this timer is reached, the subject's response will be recorded as null for the trial and the trial will end. If the value of this parameter is null, the trial will wait for a response indefinitely.
margin_vertical | string | '0px' | Vertical margin of the button(s).
margin_horizontal | string | '8px' | Horizontal margin of the button(s).
response_ends_trial | boolean | true | If true, then the trial will end whenever the subject makes a response (assuming they make their response before the cutoff specified by the `trial_duration` parameter). If false, then the trial will continue until the value for `timing_response` is reached. You can use this parameter to force the subject to view a stimulus for a fixed amount of time, even if they respond before the time is complete.
response_ends_trial | boolean | true | If true, then the trial will end whenever the subject makes a response (assuming they make their response before the cutoff specified by the `trial_duration` parameter). If false, then the trial will continue until the value for `trial_duration` is reached. You can set this parameter to `false` to force the subject to view a stimulus for a fixed amount of time, even if they respond before the time is complete.
render_on_canvas | boolean | true | If true, the image will be drawn onto a canvas element. This prevents a blank screen (white flash) between consecutive image trials in some browsers, like Firefox and Edge. If false, the image will be shown via an img element, as in previous versions of jsPsych.
## Data Generated
In addition to the [default data collected by all plugins](overview#datacollectedbyplugins), this plugin collects the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the stimulus first appears on the screen until the subject's response.
button_pressed | numeric | Indicates which button the subject pressed. The first button in the `choices` array is 0, the second is 1, and so on.
response | numeric | Indicates which button the subject pressed. The first button in the `choices` array is 0, the second is 1, and so on.
stimulus | string | The path of the image that was displayed.
## Examples

View File

@ -2,32 +2,34 @@
This plugin displays and image and records responses generated with the keyboard. The stimulus can be displayed until a response is given, or for a pre-determined amount of time. The trial can be ended automatically if the subject has failed to respond within a fixed length of time.
Image files can be automatically preloaded by jsPsych using the [`preload` plugin](jspsych-preload.md). However, if you are using timeline variables or another dynamic method to specify the image stimulus, you will need to [manually preload](/overview/media-preloading/#manual-preloading) the images.
## Parameters
Parameters with a default value of undefined must be specified. Other parameters can be left unspecified if the default value is acceptable.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of undefined must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
stimulus | string | *undefined* | The path of the image file to be displayed.
stimulus_height | integer | null | Set the height of the image in pixels. If left null (no value specified), then the image will display at its natural height.
stimulus_width | integer | null | Set the width of the image in pixels. If left null (no value specified), then the image will display at its natural width.
maintain_aspect_ration | boolean | true | If setting *only* the width or *only* the height and this parameter is true, then the other dimension will be scaled to maintain the image's aspect ratio.
choices | array of keycodes | `jsPsych.ALL_KEYS` | This array contains the keys that the subject is allowed to press in order to respond to the stimulus. Keys can be specified as their [numeric key code](http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes) or as characters (e.g., `'a'`, `'q'`). The default value of `jsPsych.ALL_KEYS` means that all keys will be accepted as valid responses. Specifying `jsPsych.NO_KEYS` will mean that no responses are allowed.
prompt | string | null | This string can contain HTML markup. Any content here will be displayed below the stimulus. The intention is that it can be used to provide a reminder about the action the subject is supposed to take (e.g., which key to press).
stimulus_duration | numeric | null | How long to show the stimulus for in milliseconds. If the value is null, then the stimulus will be shown until the subject makes a response.
trial_duration | numeric | null | How long to wait for the subject to make a response before ending the trial in milliseconds. If the subject fails to make a response before this timer is reached, the subject's response will be recorded as null for the trial and the trial will end. If the value of this parameter is null, then the trial will wait for a response indefinitely.
response_ends_trial | boolean | true | If true, then the trial will end whenever the subject makes a response (assuming they make their response before the cutoff specified by the `timing_response` parameter). If false, then the trial will continue until the value for `trial_duration` is reached. You can use this parameter to force the subject to view a stimulus for a fixed amount of time, even if they respond before the time is complete.
| Parameter | Type | Default Value | Description |
| --------------------- | ---------------- | ------------------ | ---------------------------------------- |
| stimulus | string | *undefined* | The path of the image file to be displayed. |
| stimulus_height | integer | null | Set the height of the image in pixels. If left null (no value specified), then the image will display at its natural height. |
| stimulus_width | integer | null | Set the width of the image in pixels. If left null (no value specified), then the image will display at its natural width. |
| maintain_aspect_ratio | boolean | true | If setting *only* the width or *only* the height and this parameter is true, then the other dimension will be scaled to maintain the image's aspect ratio. |
| choices | array of strings | `jsPsych.ALL_KEYS` | This array contains the key(s) that the subject is allowed to press in order to respond to the stimulus. Keys should be specified as characters (e.g., `'a'`, `'q'`, `' '`, `'Enter'`, `'ArrowDown'`) - see [this page](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values) and [this page (event.key column)](https://www.freecodecamp.org/news/javascript-keycode-list-keypress-event-key-codes/) for more examples. Any key presses that are not listed in the array will be ignored. The default value of `jsPsych.ALL_KEYS` means that all keys will be accepted as valid responses. Specifying `jsPsych.NO_KEYS` will mean that no responses are allowed. |
| prompt | string | null | This string can contain HTML markup. Any content here will be displayed below the stimulus. The intention is that it can be used to provide a reminder about the action the subject is supposed to take (e.g., which key to press). |
| stimulus_duration | numeric | null | How long to show the stimulus for in milliseconds. If the value is `null`, then the stimulus will be shown until the subject makes a response. |
| trial_duration | numeric | null | How long to wait for the subject to make a response before ending the trial in milliseconds. If the subject fails to make a response before this timer is reached, the subject's response will be recorded as null for the trial and the trial will end. If the value of this parameter is `null`, then the trial will wait for a response indefinitely. |
| response_ends_trial | boolean | true | If true, then the trial will end whenever the subject makes a response (assuming they make their response before the cutoff specified by the `trial_duration` parameter). If false, then the trial will continue until the value for `trial_duration` is reached. You can set this parameter to `false` to force the subject to view a stimulus for a fixed amount of time, even if they respond before the time is complete. |
| render_on_canvas | boolean | true | If `true`, the image will be drawn onto a canvas element. This prevents a blank screen (white flash) between consecutive image trials in some browsers, like Firefox and Edge. If `false`, the image will be shown via an img element, as in previous versions of jsPsych. |
## Data Generated
In addition to the [default data collected by all plugins](overview#datacollectedbyplugins), this plugin collects the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
key_press | numeric | Indicates which key the subject pressed. The value is the [numeric key code](http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes) corresponding to the subject's response.
rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the stimulus first appears on the screen until the subject's response.
stimulus | string | The path of the image that was displayed.
| Name | Type | Value |
| --------- | ------- | ---------------------------------------- |
| response | string | Indicates which key the subject pressed. |
| rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the stimulus first appears on the screen until the subject's response. |
| stimulus | string | The path of the image that was displayed. |
## Examples

View File

@ -2,9 +2,11 @@
This plugin displays and image and allows the subject to respond by dragging a slider.
Image files can be automatically preloaded by jsPsych using the [`preload` plugin](jspsych-preload.md). However, if you are using timeline variables or another dynamic method to specify the image stimulus, you will need to [manually preload](/overview/media-preloading/#manual-preloading) the images.
## Parameters
Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
@ -16,24 +18,26 @@ labels | array of strings | [] | Labels displayed at equidistant locations on th
button_label | string | 'Continue' | Label of the button to advance/submit
min | integer | 0 | Sets the minimum value of the slider
max | integer | 100 | Sets the maximum value of the slider
start | integer | 50 | Sets the starting value of the slider
slider_start | integer | 50 | Sets the starting value of the slider
step | integer | 1 | Sets the step of the slider
slider_width | integer | null | Set the width of the slider in pixels. If left null, then the width will be equal to the widest element in the display.
require_movement | boolean | false | If true, the subject must move the slider before clicking the continue button.
prompt | string | null | This string can contain HTML markup. Any content here will be displayed below the stimulus. The intention is that it can be used to provide a reminder about the action the subject is supposed to take (e.g., which key to press).
stimulus_duration | numeric | null | How long to show the stimulus for in milliseconds. If the value is null, then the stimulus will be shown until the subject makes a response.
trial_duration | numeric | null | How long to wait for the subject to make a response before ending the trial in milliseconds. If the subject fails to make a response before this timer is reached, the subject's response will be recorded as null for the trial and the trial will end. If the value of this parameter is null, then the trial will wait for a response indefinitely.
response_ends_trial | boolean | true | If true, then the trial will end whenever the subject makes a response (assuming they make their response before the cutoff specified by the `timing_response` parameter). If false, then the trial will continue until the value for `trial_duration` is reached. You can use this parameter to force the subject to view a stimulus for a fixed amount of time, even if they respond before the time is complete.
response_ends_trial | boolean | true | If true, then the trial will end whenever the subject makes a response (assuming they make their response before the cutoff specified by the `trial_duration` parameter). If false, then the trial will continue until the value for `trial_duration` is reached. You can set this parameter to `false` to force the subject to view a stimulus for a fixed amount of time, even if they respond before the time is complete.
render_on_canvas | boolean | true | If true, the image will be drawn onto a canvas element. This prevents a blank screen (white flash) between consecutive image trials in some browsers, like Firefox and Edge. If false, the image will be shown via an img element, as in previous versions of jsPsych.
## Data Generated
In addition to the [default data collected by all plugins](overview#datacollectedbyplugins), this plugin collects the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
response | numeric | The numeric value of the slider.
rt | numeric | The time in milliseconds for the subject to make a response. The time is measured from when the stimulus first appears on the screen until the subject's response.
stimulus | string | The path of the image that was displayed.
slider_start | numeric | The starting value of the slider.
## Examples

View File

@ -2,30 +2,31 @@
This plugin is for showing instructions to the subject. It allows subjects to navigate through multiple pages of instructions at their own pace, recording how long the subject spends on each page. Navigation can be done using the mouse or keyboard. Subjects can be allowed to navigate forwards and backwards through pages, if desired.
## Parameters
## Parameters
Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
pages | array | *undefined* | Each element of the array is the content for a single page. Each page should be an HTML-formatted string.
key_forward | key code | 'rightarrow' | This is the key that the subject can press in order to advance to the next page. Keys can be specified as their [numeric key code](http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes) or as characters (e.g., `'a'`, `'q'`).
key_backward | key code | 'leftarrow' | This is the key that the subject can press to return to the previous page.
allow_backward | boolean | true | If true, the subject can return to previous pages of the instructions. If false, they may only advace to the next page.
allow_keys | boolean | true | If true, the subject can use keyboard keys to navigate the pages. If false, they may not.
show_clickable_nav | boolean | false | If true, then a `Previous` and `Next` button will be displayed beneath the instructions. Subjects can click the buttons to navigate.
button_label_previous | string | 'Previous' | The text that appears on the button to go backwards.
button_label_next | string | 'Next' | The text that appears on the button to go forwards.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
| Parameter | Type | Default Value | Description |
| --------------------- | ------- | ------------- | ---------------------------------------- |
| pages | array | *undefined* | Each element of the array is the content for a single page. Each page should be an HTML-formatted string. |
| key_forward | string | 'ArrowRight' | This is the key that the subject can press in order to advance to the next page. This key should be specified as a string (e.g., `'a'`, `'ArrowLeft'`, `' '`, `'Enter'`). |
| key_backward | string | 'ArrowLeft' | This is the key that the subject can press to return to the previous page. This key should be specified as a string (e.g., `'a'`, `'ArrowLeft'`, `' '`, `'Enter'`). |
| allow_backward | boolean | true | If true, the subject can return to previous pages of the instructions. If false, they may only advace to the next page. |
| allow_keys | boolean | true | If `true`, the subject can use keyboard keys to navigate the pages. If `false`, they may not. |
| show_clickable_nav | boolean | false | If true, then a `Previous` and `Next` button will be displayed beneath the instructions. Subjects can click the buttons to navigate. |
| button_label_previous | string | 'Previous' | The text that appears on the button to go backwards. |
| button_label_next | string | 'Next' | The text that appears on the button to go forwards. |
| show_page_number | boolean | false | If true, and clickable navigation is enabled, then Page x/y will be shown between the nav buttons. |
| page_label | string | 'Page' | The text that appears before x/y pages displayed when show_page_number is true. |
## Data Generated
In addition to the [default data collected by all plugins](overview#datacollectedbyplugins), this plugin collects the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
view_history | JSON string | A JSON string containing the order of pages the subject viewed (including when the subject returned to previous pages) and the time spent viewing each page.
rt | numeric | The response time in milliseconds for the subject to view all of the pages.
| Name | Type | Value |
| ------------ | ----------- | ---------------------------------------- |
| view_history | array | An array containing the order of pages the subject viewed (including when the subject returned to previous pages) and the time spent viewing each page. Each object in the array represents a single page view, and contains keys called `page_index` (the page number, starting with 0) and `viewing_time` (duration of the page view). This will be encoded as a JSON string when data is saved using the `.json()` or `.csv()` functions. |
| rt | numeric | The response time in milliseconds for the subject to view all of the pages. |
## Example

View File

@ -0,0 +1,41 @@
# jspsych-maxdiff plugin
The maxdiff plugin displays a table with rows of alternatives to be selected for two mutually-exclusive categories, typically as 'most' or 'least' on a particular criteria (e.g. importance, preference, similarity). The participant responds by selecting one radio button corresponding to an alternative in both the left and right response columns. The same alternative cannot be endorsed on both the left and right response columns (e.g. 'most' and 'least') simultaneously.
## Parameters
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
alternatives | array | *undefined* | An array of one or more alternatives of string type to fill the rows of the maxdiff table. If `required` is true, then the array must contain two or more alternatives, so that at least one can be selected for both the left and right columns.
labels | array | *undefined* | An array with exactly two labels of string type to display as column headings (to the left and right of the alternatives) for responses on the criteria of interest.
randomize_alternative_order | boolean | `false` | If true, the display order of `alternatives` is randomly determined at the start of the trial.
preamble | string | empty string | HTML formatted string to display at the top of the page above the maxdiff table.
required | boolean | `false` | If true, prevents the user from submitting the response and proceeding until a radio button in both the left and right response columns has been selected.
button_label | string | 'Continue' | Label of the button.
## Data Generated
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the maxdiff table first appears on the screen until the subject's response.
labels | object | An object with two keys, `left` and `right`, containing the labels (strings) corresponding to the left and right response columns. This will be encoded as a JSON string when data is saved using the `.json()` or `.csv()` functions.
response | object | An object with two keys, `left` and `right`, containing the alternatives selected on the left and right columns. This will be encoded as a JSON string when data is saved using the `.json()` or `.csv()` functions.
## Examples
#### Basic example
```javascript
var maxdiff_page = {
type: 'maxdiff',
alternatives: ['apple', 'orange', 'pear', 'banana'],
labels: ['Most Preferred', 'Least Preferred'],
preamble: '<p> Please select your <b>most preferred</b> and <b>least preferred</b> fruits. </p>'
};
```

View File

@ -0,0 +1,128 @@
# jspsych-preload
This plugin loads images, audio, and video files. It is used for loading files into the browser's memory before they are needed in the experiment, in order to improve stimulus and response timing, and avoid disruption to the experiment flow. We recommend using this plugin anytime you are loading media files, and especially when your experiment requires large and/or many media files. See the [Media Preloading page](/overview/media-preloading.md) for more information.
The preload trial will end as soon as all files have loaded successfully. The trial will end or stop with an error message when one of these two scenarios occurs (whichever comes first): (a) all files have not finished loading when the `max_load_time` duration is reached, or (b) all file requests have responded with either a load or fail event, and one or more files has failed to load. The `continue_after_error` parameter determines whether the trial will stop with an error message or end (allowing the experiment to continue) when preloading is not successful.
## Parameters
In addition to the [parameters available in all plugins](/overview/plugins.md#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.
All other parameters can be left unspecified if the default value is acceptable.
| 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. |
| 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.md) 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. |
| 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. |
| video | array | [] | Array containing file paths for one or more video files to preload. This option is typically used for video files that can't be automatically preloaded from the timeline. |
| message | HTML string | null | HTML-formatted message to show above the progress bar while the files are loading. If `null`, then no message is shown. |
| show_progress_bar | boolean | true | If `true`, a progress bar will be shown while the files are loading. If `false`, no progress bar is shown. |
| continue_after_error | boolean | false | If `false`, then the experiment will stop during this trial if either (a) one or more of the files fails to load, and/or (b) all files do not finish loading before the `max_load_time` duration is reached. The trial will display the `error_message`, as well as the detailed error messages if `show_detailed_errors` is `true`. If `true`, the experiment will continue even if loading fails or times out, and information about loading success/failure will be stored in the trial data (see "Data Generated" below). |
| error_message | HTML string | 'The experiment failed to load.' | HTML-formatted message to be shown on the page after loading fails or times out. Only applies when `continue_after_error` is `false`. |
| show_detailed_errors | boolean | false | If `true`, and if `continue_after_error` is `false`, then a list of detailed errors will be shown below the `error_message`. This list will contain the file paths for any files that produced a loading failure, as well as a message indicating that loading timed out, if that was the case. This setting is intended to help the researcher with testing/debugging. If `false`, and if `continue_after_error` is `false`, then only the `error_message` will be shown if loading fails or times out. |
| max_load_time | numeric | null | Duration to wait, in milliseconds, for all files to load before loading times out. If one or more files has not finished loading within this time limit, then the trial will stop with an error (if `continue_after_error` is `false`), or the trial will end with information about the loading time-out in the trial data (see "Data Generated" below). If `null`, the trial will wait indefinitely for all files to either load or produce an error. |
| on_error | function | null | Function to be called immediately after a file loading request has returned an error. The function receives a single argument, which is the file path that produced the error. This callback is cancelled as soon as the trial ends. See example below. |
| on_success | function | null | Function to be called immediately after a file has successfully loaded. The function receives a single argument, which is the file path that finished loading. This callback is cancelled as soon as the trial ends. See example below. |
## Data Generated
In addition to the [default data collected by all plugins](/overview/plugins.md#data-collected-by-plugins), this plugin collects the following data for each trial.
| Name | Type | Value |
| -------------- | ------- | ---------------------------------------- |
| success | boolean | If `true`, then all files loaded successfully within the `max_load_time`. If `false`, then one or more file requests returned a failure and/or the file loading did not complete within the `max_load_time` duration. |
| timeout | boolean | If `true`, then the files did not finish loading within the `max_load_time` duration. If `false`, then the file loading did not timeout. Note that when the preload trial does not timeout (`timeout: false`), it is still possible for loading to fail (`success: false`). This happens if one or more files fails to load and all file requests trigger either a success or failure event before the `max_load_time` duration. |
| failed_images | array | One or more image file paths that produced a loading failure before the trial ended. |
| failed_audio | array | One or more audio file paths that produced a loading failure before the trial ended. |
| failed_video | array | One or more video file paths that produced a loading failure before the trial ended. |
## Examples
#### Loading files automatically based on the main timeline
```javascript
var preload = {
type: 'preload',
auto_preload: true // automatically load all files based on the main timeline
};
// define other trials to add to the timeline...
jsPsych.init({
timeline: [preload, trial1, trial2, trial3]
});
```
#### Loading files manually
```javascript
var preload = {
type: 'preload',
images: ['file1.png']
};
```
#### Combining automatic and manual methods
```javascript
// automatically load stimuli from the main timeline,
// and manually add any other stimuli files that can't be loaded automatically
var preload = {
type: 'preload',
auto_preload: true,
images: ['image1.png','image2.png']
};
// define other trials to add to the timeline...
jsPsych.init({
timeline: [preload, trial1, trial2, trial3]
});
```
#### Loading files in batches
```javascript
var block_1 = {
timeline: [...]
}
var block_2 = {
timeline: [...]
}
var preload_1 = {
type: 'preload',
trials: block_1 // automatically load block_1 stimuli
};
var preload_2 = {
type: 'preload',
trials: block_2 // automatically load block_2 stimuli
};
jsPsych.init(
// add each preload trial to the timeline before the appropriate trial block
timeline: [preload_1, block_1, preload_2, block_2]
)
```
#### Using the on_success and on_error functions
```javascript
var preload = {
type: 'preload',
audio: ['sound.mp3'],
on_success: function(file) {
console.log('File loaded: ',file);
},
on_error: function(file) {
console.log('Error loading file: ',file);
}
};
```
For more examples, see the `jspsych-preload.html` file in the jsPsych examples folder and the [Media Preloading](/overview/media-preloading.md) documentation page.

View File

@ -5,44 +5,44 @@ This plugin displays a Random Dot Kinematogram (RDK) and allows the subject to r
We would appreciate it if you cited this paper when you use the RDK:
<b>Rajananda, S., Lau, H. & Odegaard, B., (2018). A Random-Dot Kinematogram for Web-Based Vision Research. Journal of Open Research Software. 6(1), p.6. DOI: [http://doi.org/10.5334/jors.194]</b>
For optimal performance, fullscreen mode should be manually triggered by the user (e.g. F11 key in Chrome for Windows). Usage of the default Fullscreen trigger from the JsPsych API library with this plugin might result in the stimuli being displayed incorrectly.
For optimal performance, fullscreen mode should be manually triggered by the user (e.g. F11 key in Chrome for Windows). Usage of the default Fullscreen trigger from the jsPsych API library with this plugin might result in the stimuli being displayed incorrectly.
## Parameters
Parameters can be left unspecified if the default value is acceptable.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Parameters can be left unspecified if the default value is acceptable.
|Parameter|Type|Default Value| Descripton|
|---------|----|-------------|-----------|
|choices|array|[]|The valid keys that the subject can press as a response. Must be an array of chars or numbers (corresponding to JavaScript character codes). If left unspecified, any key is a valid key.|
|correct_choice|array, char, or number|undefined|The keys that are considered the correct response for that particular trial. Can be a single char, a single number, an array of chars, or an array of numbers. Numbers here correspond to the JavaScript character codes. This needs to be linked with the `coherent_direction` parameter (See Examples section below for an illustration.) This is used to determine whether the subject chose the correct response. The boolean indicating whether or not the subject chose the correct response is returned in the `correct` key of the data object. |
|trial_duration|numeric|500|The amount of time that the stimulus is displayed on the screen in ms. If -1, the stimulus will be displayed until the subject keys in a valid response. (`choices` parameter must contain valid keys or else the stimuli will run indefinitely).|
|response_ends_trial|boolean|true|If true, then the subject's response will end the trial. If false, the stimuli will be presented for the full `trial_duration` (the response will be recorded as long as the subject responds within the trial duration).|
|number_of_apertures|numeric|1|The number of apertures or RDKs on the screen. If set to more than one, remember to set the location (i.e., aperture_center_x and aperture_center_y) parameters to separate them. <br>In addition, each aperture can be customized individually by passing in an array of values as the parameter (see example below). If a single value (not an array) is passed as the parameter, then all apertures will have the same parameter.|
|number_of_dots|numeric|300|Number of dots per set. Equivalent to number of dots per frame.|
|number_of_sets|numeric|1|Number of sets to cycle through. Each frame displays one set of dots. (E.g. If 2 sets of dots, frame 1 will display dots from set 1, frame 2 will display dots from set 2, frame 3 will display sets from set 1, etc.)|
|coherent_direction|numeric|0|The direction of movement for coherent dots in degrees. 0 degrees is in the 3 o'clock direction, and increasing this number moves counterclockwise. (E.g. 12 o'clock is 90, 9 o'clock is 180, etc.) Range is 0 - 360.|
|coherence|numeric|0.5|The proportion of dots that move together in the coherent direction. Range is 0 to 1.|
|opposite_coherence|numeric|0|The proportion of moving in the direction opposite of the coherent direction. Range is 0 to (1-coherence).|
|dot_radius|numeric|2|The radius of each individual dot in pixels.|
|dot_life|numeric|-1|The number of frames that pass before a dot disappears and reappears in a new frame. -1 denotes that the dot life is infinite (i.e., a dot will only disappear and reappear if it moves out of the aperture).|
|move_distance|numeric|1|The number of pixel lengths the dot will move in each frame (analogous to speed of dots).|
|aperture_width|numeric|600|The width of the aperture in pixels. For a square aperture, this will determine both the width and height. For circular aperture, this will determine the diameter.|
|aperture_height|numeric|400|The height of the aperture in pixels. For square and circle apertures, this will be ignored.|
|dot_color|string|"white"|The color of the dots.|
|background_color|string|"gray"|The color of the background.|
|RDK_type|numeric|3|The Signal Selection Rule (Same/Different) and Noise Type (Random Position/Walk/Direction):<br><br>1 - Same && Random Position<br>2 - Same && Random Walk<br>3 - Same && Random Direction<br>4 - Different && Random Position<br>5 - Different && Random Walk<br>6 - Different && Random Direction<br><br>(See 'RDK parameter' below for more detailed information)<br>|
|aperture_type|numeric|2|The shape of the aperture.<br><br>1 - Circle<br>2 - Ellipse<br>3 - Square<br>4 - Rectangle<br>|
|reinsert_type|numeric|2|The type of reinsertion of a dot that has gone out of bounds<br><br>1 - Randomly appear anywhere in the aperture<br>2 - Appear on the opposite edge of the aperture. For squares and rectangles, a random point on the opposite edge is chosen as the reinsertion point. For circles and ellipses, the exit point is reflected about center to become the reinsertion point.<br>|
|aperture_center_x|numeric|window.innerWidth/2|The x-coordinate of the center of the aperture, in pixels.<br>|
|aperture_center_y|numeric|window.innerHeight/2|The y-coordinate of the center of the aperture, in pixels.<br>|
|fixation_cross|boolean|false|Whether or not a fixation cross is presented in the middle of the screen.<br>|
|fixation_cross_width|numeric|20|The width of the fixation cross in pixels.<br>|
|fixation_cross_height|numeric|20|The height of the fixation cross in pixels.<br>|
|fixation_cross_color|string|"black"|The color of the fixation cross.<br>|
|fixation_cross_thickness|numeric|1|The thickness of the fixation cross in pixels.<br>|
|border|boolean|false|The presence of a border around the aperture.<br>|
|border_thickness|numeric|1|The thickness of the border in pixels.<br>|
|border_color|string|"black"|The color of the border.<br>|
| Parameter | Type | Default Value | Descripton |
| ------------------------ | ---------------- | -------------------- | ---------------------------------------- |
| choices | array of strings | jsPsych.ALL_KEYS | The valid keys that the subject can press as a response. Must be an array of strings. If left unspecified, any key is a valid key. |
| correct_choice | array or string | *undefined* | The keys that are considered the correct response for that particular trial. Can be a single string or an array of strings. This needs to be linked with the `coherent_direction` parameter (see Examples section below for an illustration). This is used to determine whether the subject chose the correct response. The boolean indicating whether or not the subject chose the correct response is returned in the `correct` key of the data object. |
| trial_duration | numeric | 500 | The amount of time that the stimulus is displayed on the screen in ms. If -1, the stimulus will be displayed until the subject keys in a valid response. (`choices` parameter must contain valid keys or else the stimuli will run indefinitely). |
| response_ends_trial | boolean | true | If `true`, then the subject's response will end the trial. If `false`, the stimuli will be presented for the full `trial_duration` (the response will be recorded as long as the subject responds within the trial duration). |
| number_of_apertures | numeric | 1 | The number of apertures or RDKs on the screen. If set to more than one, remember to set the location (i.e., aperture_center_x and aperture_center_y) parameters to separate them. <br>In addition, each aperture can be customized individually by passing in an array of values as the parameter (see example below). If a single value (not an array) is passed as the parameter, then all apertures will have the same parameter. |
| number_of_dots | numeric | 300 | Number of dots per set. Equivalent to number of dots per frame. |
| number_of_sets | numeric | 1 | Number of sets to cycle through. Each frame displays one set of dots. (E.g. If 2 sets of dots, frame 1 will display dots from set 1, frame 2 will display dots from set 2, frame 3 will display sets from set 1, etc.) |
| coherent_direction | numeric | 0 | The direction of movement for coherent dots in degrees. 0 degrees is in the 3 o'clock direction, and increasing this number moves counterclockwise. (E.g. 12 o'clock is 90, 9 o'clock is 180, etc.) Range is 0 - 360. |
| coherence | numeric | 0.5 | The proportion of dots that move together in the coherent direction. Range is 0 to 1. |
| opposite_coherence | numeric | 0 | The proportion of moving in the direction opposite of the coherent direction. Range is 0 to (1-coherence). |
| dot_radius | numeric | 2 | The radius of each individual dot in pixels. |
| dot_life | numeric | -1 | The number of frames that pass before a dot disappears and reappears in a new frame. -1 denotes that the dot life is infinite (i.e., a dot will only disappear and reappear if it moves out of the aperture). |
| move_distance | numeric | 1 | The number of pixel lengths the dot will move in each frame (analogous to speed of dots). |
| aperture_width | numeric | 600 | The width of the aperture in pixels. For a square aperture, this will determine both the width and height. For circular aperture, this will determine the diameter. |
| aperture_height | numeric | 400 | The height of the aperture in pixels. For square and circle apertures, this will be ignored. |
| dot_color | string | "white" | The color of the dots. |
| background_color | string | "gray" | The color of the background. |
| RDK_type | numeric | 3 | The Signal Selection Rule (Same/Different) and Noise Type (Random Position/Walk/Direction):<br><br>1 - Same && Random Position<br>2 - Same && Random Walk<br>3 - Same && Random Direction<br>4 - Different && Random Position<br>5 - Different && Random Walk<br>6 - Different && Random Direction<br><br>(See 'RDK parameter' below for more detailed information)<br> |
| aperture_type | numeric | 2 | The shape of the aperture.<br><br>1 - Circle<br>2 - Ellipse<br>3 - Square<br>4 - Rectangle<br> |
| reinsert_type | numeric | 2 | The type of reinsertion of a dot that has gone out of bounds<br><br>1 - Randomly appear anywhere in the aperture<br>2 - Appear on the opposite edge of the aperture. For squares and rectangles, a random point on the opposite edge is chosen as the reinsertion point. For circles and ellipses, the exit point is reflected about center to become the reinsertion point.<br> |
| aperture_center_x | numeric | window.innerWidth/2 | The x-coordinate of the center of the aperture, in pixels.<br> |
| aperture_center_y | numeric | window.innerHeight/2 | The y-coordinate of the center of the aperture, in pixels.<br> |
| fixation_cross | boolean | false | Whether or not a fixation cross is presented in the middle of the screen.<br> |
| fixation_cross_width | numeric | 20 | The width of the fixation cross in pixels.<br> |
| fixation_cross_height | numeric | 20 | The height of the fixation cross in pixels.<br> |
| fixation_cross_color | string | "black" | The color of the fixation cross.<br> |
| fixation_cross_thickness | numeric | 1 | The thickness of the fixation cross in pixels.<br> |
| border | boolean | false | The presence of a border around the aperture.<br> |
| border_thickness | numeric | 1 | The thickness of the border in pixels.<br> |
| border_color | string | "black" | The color of the border.<br> |
### RDK type parameter
** See Fig. 1 in Scase, Braddick, and Raymond (1996) for a visual depiction of these different signal selection rules and noise types.
@ -59,19 +59,18 @@ Parameters can be left unspecified if the default value is acceptable.
## Data Generated
In addition to the default data collected by all plugins, this plugin collects all parameter data described above and the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects all parameter data described above and the following data for each trial.
|Name|Type|Value|
|----|----|-----|
|rt|numeric|The response time in ms for the subject to make a response.|
|key_press|numeric|The key that the subject pressed. The value corresponds to the Javascript Char Code (Key Code).|
|correct|boolean|Whether or not the subject's key press corresponded to those provided in correct_choice.|
|frame_rate|numeric|The average frame rate for the trial. 0 denotes that the subject responded before the appearance of the second frame.|
|number_of_frames|numeric|The number of frames that was shown in this trial.|
|frame_rate_array|JSON string|The array that holds the number of miliseconds for each frame in this trial.|
|canvas_width|numeric|The width of the canvas in pixels.|
|canvas_height|numeric|The height of the canvas in pixels.|
| Name | Type | Value |
| ---------------- | ----------- | ---------------------------------------- |
| rt | numeric | The response time in ms for the subject to make a response. |
| response | string | The key that the subject pressed. |
| correct | boolean | Whether or not the subject's key press corresponded to those provided in correct_choice. |
| frame_rate | numeric | The average frame rate for the trial. 0 denotes that the subject responded before the appearance of the second frame. |
| number_of_frames | numeric | The number of frames that was shown in this trial. |
| frame_rate_array | array | The array that holds the number of miliseconds for each frame in this trial. This will be encoded as a JSON string when data is saved using the `.json()` or `.csv()` functions. |
| canvas_width | numeric | The width of the canvas in pixels. |
| canvas_height | numeric | The height of the canvas in pixels. |
## Example
@ -80,12 +79,12 @@ In addition to the default data collected by all plugins, this plugin collects a
```javascript
var trial_right = {
coherent_direction: 0,
correct_choice: "P"
correct_choice: "p"
};
var trial_left = {
coherent_direction: 180,
correct_choice: "Q"
correct_choice: "q"
};
```

View File

@ -6,20 +6,20 @@ The stimulus must be defined through a function that returns an HTML-formatted s
## Parameters
Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
stim_function | function | *undefined* | A function with a single parameter that returns an HTML-formatted string representing the stimulus.
starting_value | numeric | 0.5 | The starting value of the stimulus parameter.
step_size | numeric | 0.05 | The change in the stimulus parameter caused by pressing one of the modification keys.
key_increase | key code | 'h' | The key to press for increasing the parameter value.
key_decrease | key code | 'g' | The key to press for decreasing the parameter value.
key_increase | string | 'h' | The key to press for increasing the parameter value.
key_decrease | string | 'g' | The key to press for decreasing the parameter value.
button_label | string | 'Continue' | The text that appears on the button to finish the trial.
## Data Generated
In addition to the [default data collected by all plugins](overview#datacollectedbyplugins), this plugin collects the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------

View File

@ -4,7 +4,7 @@ This plugin displays a resizable div container that allows the user to drag unti
## Parameters
Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
@ -15,6 +15,15 @@ prompt | string | `''` | HTML content to display below the resizable box, and ab
button_label | string | 'Continue' | Label to display on the button to complete calibration.
starting_size | numeric | 100 | The initial size of the box, in pixels, along the largest dimension. The aspect ratio will be set automatically to match the item width and height.
## Data Generated
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
final_width_px | numeric | Final width of the resizable div container, in pixels.
scale_factor | numeric | Scaling factor that will be applied to the div containing jsPsych content.
## Examples
#### Measuring a credit card and resizing the display to have 150 pixels equal an inch.

View File

@ -4,38 +4,38 @@ The same-different-html plugin displays two stimuli sequentially. Stimuli are HT
## Parameters
Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
stimuli | array | *undefined* | A pair of stimuli, represented as an array with two entries, one for each stimulus. A stimulus is a string containing valid HTML markup. Stimuli will be shown in the order that they are defined in the array.
answer | string | *undefined* | Either `'same'` or `'different'`.
same_key | numeric or string | 'Q' | The key that subjects should press to indicate that the two stimuli are the same.
different_key | numeric or string | 'P' | The key that subjects should press to indicate that the two stimuli are different.
timing_first_stim | numeric | 1000 | How long to show the first stimulus for in milliseconds. If the value of this parameter is null then the stimulus will be shown until the subject presses any key.
timing_gap | numeric | 500 | How long to show a blank screen in between the two stimuli.
timing_second_stim | numeric | 1000 | How long to show the second stimulus for in milliseconds. If the value of this parameter is null then the stimulus will be shown until the subject responds.
prompt | string | null | This string can contain HTML markup. Any content here will be displayed below the stimulus. The intention is that it can be used to provide a reminder about the action the subject is supposed to take (e.g., which key to press).
| Parameter | Type | Default Value | Description |
| -------------------- | ------- | ------------- | ---------------------------------------- |
| stimuli | array | *undefined* | A pair of stimuli, represented as an array with two entries, one for each stimulus. A stimulus is a string containing valid HTML markup. Stimuli will be shown in the order that they are defined in the array. |
| answer | string | *undefined* | Either `'same'` or `'different'`. |
| same_key | string | 'q' | The key that subjects should press to indicate that the two stimuli are the same. |
| different_key | string | 'p' | The key that subjects should press to indicate that the two stimuli are different. |
| first_stim_duration | numeric | 1000 | How long to show the first stimulus for in milliseconds. If the value of this parameter is null then the stimulus will be shown until the subject presses any key. |
| gap_duration | numeric | 500 | How long to show a blank screen in between the two stimuli. |
| second_stim_duration | numeric | 1000 | How long to show the second stimulus for in milliseconds. If the value of this parameter is null then the stimulus will be shown until the subject responds. |
| prompt | string | null | This string can contain HTML markup. Any content here will be displayed below the stimulus. The intention is that it can be used to provide a reminder about the action the subject is supposed to take (e.g., which key to press). |
## Data Generated
In addition to the [default data collected by all plugins](overview#datacollectedbyplugins), this plugin collects the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
stimulus | string | An JSON-encoded array of length 2 containing either the path to the image file or the string containing the HTML formatted content that the subject saw for each trial.
key_press | numeric | Indicates which key the subject pressed. The value is the [numeric key code](http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes) corresponding to the subject's response.
rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the second stimulus first appears on the screen until the subject's response.
correct | boolean | `true` if the subject's response matched the `answer` for this trial.
answer | string | The correct answer to the trial, either `'same'` or `'different'`.
| Name | Type | Value |
| --------- | ------- | ---------------------------------------- |
| stimulus | array | An array of length 2 containing the HTML-formatted content that the subject saw for each trial. This will be encoded as a JSON string when data is saved using the `.json()` or `.csv()` functions. |
| response | string | Indicates which key the subject pressed. |
| rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the second stimulus first appears on the screen until the subject's response. |
| correct | boolean | `true` if the subject's response matched the `answer` for this trial. |
| answer | string | The correct answer to the trial, either `'same'` or `'different'`. |
Additionally, if `timing_first_stim` is null, then the following data is also collected:
Additionally, if `first_stim_duration` is null, then the following data is also collected:
Name | Type | Value
-----|------|------
rt_stim1 | numeric | The response time in milliseconds for the subject to continue after the first stimulus. The time is measured from when the first stimulus appears on the screen until the subject's response.
key_press_stim1 | numeric | Indicates which key the subject pressed to continue. The value is the [numeric key code](http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes) corresponding to the subject's response.
| Name | Type | Value |
| --------------- | ------- | ---------------------------------------- |
| rt_stim1 | numeric | The response time in milliseconds for the subject to continue after the first stimulus. The time is measured from when the first stimulus appears on the screen until the subject's response. |
| response_stim1 | string | Indicates which key the subject pressed to continue. |
## Examples
@ -43,11 +43,11 @@ key_press_stim1 | numeric | Indicates which key the subject pressed to continue.
```javascript
var trial = {
type: 'same-different',
type: 'same-different-html',
stimuli: ['<p>Climbing</p>', '<p>Walking</p>'],
prompt: "<p>Press S if the texts imply the same amount of physical exertion. Press D if the texts imply different amount of physical exertion.</p>",
same_key: 'S',
different_key: 'D',
prompt: "<p>Press 's' if the texts imply the same amount of physical exertion. Press 'd' if the texts imply different amount of physical exertion.</p>",
same_key: 's',
different_key: 'd',
answer: 'different'
}
```

View File

@ -4,38 +4,38 @@ The same-different plugin displays two stimuli sequentially. Stimuli are image o
## Parameters
Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
stimuli | array | *undefined* | A pair of stimuli, represented as an array with two entries, one for each stimulus. The stimulus is a path to an image file. Stimuli will be shown in the order that they are defined in the array.
answer | string | *undefined* | Either `'same'` or `'different'`.
same_key | numeric or string | 'Q' | The key that subjects should press to indicate that the two stimuli are the same.
different_key | numeric or string | 'P' | The key that subjects should press to indicate that the two stimuli are different.
timing_first_stim | numeric | 1000 | How long to show the first stimulus for in milliseconds. If the value of this parameter is null then the stimulus will be shown until the subject presses any key.
timing_gap | numeric | 500 | How long to show a blank screen in between the two stimuli.
timing_second_stim | numeric | 1000 | How long to show the second stimulus for in milliseconds. If the value of this parameter is null then the stimulus will be shown until the subject responds.
prompt | string | null | This string can contain HTML markup. Any content here will be displayed below the stimulus. The intention is that it can be used to provide a reminder about the action the subject is supposed to take (e.g., which key to press).
| Parameter | Type | Default Value | Description |
| -------------------- | ------- | ------------- | ---------------------------------------- |
| stimuli | array | *undefined* | A pair of stimuli, represented as an array with two entries, one for each stimulus. The stimulus is a path to an image file. Stimuli will be shown in the order that they are defined in the array. |
| answer | string | *undefined* | Either `'same'` or `'different'`. |
| same_key | string | 'q' | The key that subjects should press to indicate that the two stimuli are the same. |
| different_key | string | 'p' | The key that subjects should press to indicate that the two stimuli are different. |
| first_stim_duration | numeric | 1000 | How long to show the first stimulus for in milliseconds. If the value of this parameter is null then the stimulus will be shown until the subject presses any key. |
| gap_duration | numeric | 500 | How long to show a blank screen in between the two stimuli. |
| second_stim_duration | numeric | 1000 | How long to show the second stimulus for in milliseconds. If the value of this parameter is null then the stimulus will be shown until the subject responds. |
| prompt | string | null | This string can contain HTML markup. Any content here will be displayed below the stimulus. The intention is that it can be used to provide a reminder about the action the subject is supposed to take (e.g., which key to press). |
## Data Generated
In addition to the [default data collected by all plugins](overview#datacollectedbyplugins), this plugin collects the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
stimulus | string | An JSON-encoded array of length 2 containing either the path to the image file or the string containing the HTML formatted content that the subject saw for each trial.
key_press | numeric | Indicates which key the subject pressed. The value is the [numeric key code](http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes) corresponding to the subject's response.
rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the second stimulus first appears on the screen until the subject's response.
correct | boolean | `true` if the subject's response matched the `answer` for this trial.
answer | string | The correct answer to the trial, either `'same'` or `'different'`.
| Name | Type | Value |
| --------- | ------- | ---------------------------------------- |
| stimulus | array | An array of length 2 containing the paths to the image files that the subject saw for each trial. This will be encoded as a JSON string when data is saved using the `.json()` or `.csv()` functions. |
| response | string | Indicates which key the subject pressed. |
| rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the second stimulus first appears on the screen until the subject's response. |
| correct | boolean | `true` if the subject's response matched the `answer` for this trial. |
| answer | string | The correct answer to the trial, either `'same'` or `'different'`. |
Additionally, if `timing_first_stim` is null, then the following data is also collected:
Additionally, if `first_stim_duration` is null, then the following data is also collected:
Name | Type | Value
-----|------|------
rt_stim1 | numeric | The response time in milliseconds for the subject to continue after the first stimulus. The time is measured from when the first stimulus appears on the screen until the subject's response.
key_press_stim1 | numeric | Indicates which key the subject pressed to continue. The value is the [numeric key code](http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes) corresponding to the subject's response.
| Name | Type | Value |
| --------------- | ------- | ---------------------------------------- |
| rt_stim1 | numeric | The response time in milliseconds for the subject to continue after the first stimulus. The time is measured from when the first stimulus appears on the screen until the subject's response. |
| response_stim1 | string | Indicates which key the subject pressed to continue. |
## Examples
@ -45,9 +45,9 @@ key_press_stim1 | numeric | Indicates which key the subject pressed to continue.
var block = {
type: 'same-different-image',
stimuli: ['img/happy_face_1.jpg', 'img/sad_face_3.jpg'],
prompt: "<p>Press S if the faces had the same emotional expression. Press D if the faces had different emotional expressions.</p>",
same_key: 'S',
different_key: 'D',
prompt: "<p>Press s if the faces had the same emotional expression. Press d if the faces had different emotional expressions.</p>",
same_key: 's',
different_key: 'd',
answer: 'different'
}
```
@ -58,9 +58,9 @@ var block = {
var block = {
type: 'same-different-image',
stimuli: ['img/happy_face_1.jpg', 'img/happy_face_3.jpg'],
prompt: "<p>Press S if the faces had the same emotional expression. Press D if the faces had different emotional expressions.</p>",
same_key: 'S',
different_key: 'D',
prompt: "<p>Press s if the faces had the same emotional expression. Press d if the faces had different emotional expressions.</p>",
same_key: 's',
different_key: 'd',
answer: 'same'
}
```

View File

@ -4,30 +4,32 @@ The serial reaction time mouse plugin implements a generalized version of the SR
## Parameters
Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
target | array | *undefined* | The location of the target. The array should be the `[row, column]` of the target.
grid | array | `[[1,1,1,1]]` | This array represents the grid of boxes shown on the screen. Each inner array represents a single row. The entries in the inner arrays represent the columns. If an entry is `1` then a square will be drawn at that location on the grid. If an entry is `0` then the corresponding location on the grid will be empty. Thus, by mixing `1`s and `0`s it is possible to create many different grid-based arrangements.
grid_square_size | numeric | 100 | The width and height in pixels of each square in the grid.
target_color | hex color code | `#999` | The color of the target square.
response_ends_trial | boolean | `true` | If true, the trial ends after a key press. Feedback is displayed if `show_response_feedback` is true.
pre_target_duration | numeric | 0 | The number of milliseconds to display the grid *before* the target changes color.
trial_duration | numeric | null | The maximum length of time of the trial, not including feedback.
fade_duration | numeric | null | If a positive number, the target will progressively change color at the start of the trial, with the transition lasting this many milliseconds.
allow_nontarget_responses | boolean | false | If true, the user can make nontarget response.
prompt | string | null | This string can contain HTML markup. Any content here will be displayed below the stimulus. The intention is that it can be used to provide a reminder about the action the subject is supposed to take (e.g., which keys to press).
| Parameter | Type | Default Value | Description |
| ------------------------- | -------------- | ------------- | ---------------------------------------- |
| target | array | *undefined* | The location of the target. The array should be the `[row, column]` of the target. |
| grid | array | `[[1,1,1,1]]` | This array represents the grid of boxes shown on the screen. Each inner array represents a single row. The entries in the inner arrays represent the columns. If an entry is `1` then a square will be drawn at that location on the grid. If an entry is `0` then the corresponding location on the grid will be empty. Thus, by mixing `1`s and `0`s it is possible to create many different grid-based arrangements. |
| grid_square_size | numeric | 100 | The width and height in pixels of each square in the grid. |
| target_color | hex color code | `#999` | The color of the target square. |
| response_ends_trial | boolean | `true` | If true, the trial ends after a mouse click. Feedback is displayed if `show_response_feedback` is true. |
| pre_target_duration | numeric | 0 | The number of milliseconds to display the grid *before* the target changes color. |
| trial_duration | numeric | null | The maximum length of time of the trial, not including feedback. |
| fade_duration | numeric | null | If a positive number, the target will progressively change color at the start of the trial, with the transition lasting this many milliseconds. |
| allow_nontarget_responses | boolean | false | If true, the user can make nontarget response. |
| prompt | string | null | This string can contain HTML markup. Any content here will be displayed below the stimulus. The intention is that it can be used to provide a reminder about the action the subject is supposed to take (e.g., which keys to press). |
## Data Generated
In addition to the [default data collected by all plugins](overview#datacollectedbyplugins), this plugin collects the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
grid | JSON | A JSON-encoded representation of the grid.
target | JSON | A JSON-encoded representation of the target on the grid.
rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the second stimulus first appears on the screen until the subject's response.
| Name | Type | Value |
| ------ | ------- | ---------------------------------------- |
| grid | array | The grid representation. Each inner array represents a single row. The entries in the inner arrays represent the columns. This will be encoded as a JSON string when data is saved using the `.json()` or `.csv()` functions. |
| target | array | The `[row, column]` target location on the grid. This will be encoded as a JSON string when data is saved using the `.json()` or `.csv()` functions. |
| rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the second stimulus first appears on the screen until the subject's response. |
| response | array | The `[row, column]` response location on the grid. This will be encoded as a JSON string when data is saved using the `.json()` or `.csv()` functions. |
| correct | boolean | Whether the response location matches the target location (`true`) or not (`false`)l
## Examples
@ -43,7 +45,7 @@ var trial = {
#### 2x2 grid with extra space in the middle
```javascript
var trial = {
type: 'serial-reaction-time',
type: 'serial-reaction-time-mouse',
grid: [[1,0,1],[0,0,0],[1,0,1]],
target: [0,2]
}

View File

@ -4,34 +4,34 @@ The serial reaction time plugin implements a generalized version of the SRT task
## Parameters
Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
target | array | *undefined* | The location of the target. The array should be the `[row, column]` of the target.
grid | array | `[[1,1,1,1]]` | This array represents the grid of boxes shown on the screen. Each inner array represents a single row. The entries in the inner arrays represent the columns. If an entry is `1` then a square will be drawn at that location on the grid. If an entry is `0` then the corresponding location on the grid will be empty. Thus, by mixing `1`s and `0`s it is possible to create many different grid-based arrangements.
choices | array | `[['3','5','7','9']]` | The dimensions of this array must match the dimensions of `grid`. Each entry in this array is the key that should be pressed for that corresponding location in the grid. Entries can be left blank if there is no key associated with that location of the grid.
grid_square_size | numeric | 100 | The width and height in pixels of each square in the grid.
target_color | hex color code | `#999` | The color of the target square.
response_ends_trial | boolean | `true` | If true, the trial ends after a key press. Feedback is displayed if `show_response_feedback` is true.
pre_target_duration | numeric | 0 | The number of milliseconds to display the grid *before* the target changes color.
trial_duration | numeric | null | The maximum length of time of the trial, not including feedback.
show_response_feedback | boolean | false | If true, show feedback indicating where the user responded and whether it was correct.
feedback_duration | numeric | 200 |The length of time in milliseconds to show the feedback.
fade_duration | numeric | null | If a positive number, the target will progressively change color at the start of the trial, with the transition lasting this many milliseconds.
prompt | string | null | This string can contain HTML markup. Any content here will be displayed below the stimulus. The intention is that it can be used to provide a reminder about the action the subject is supposed to take (e.g., which keys to press).
| Parameter | Type | Default Value | Description |
| ---------------------- | ---------------- | --------------------- | ---------------------------------------- |
| target | array | *undefined* | The location of the target. The array should be the `[row, column]` of the target. |
| grid | array | `[[1,1,1,1]]` | This array represents the grid of boxes shown on the screen. Each inner array represents a single row. The entries in the inner arrays represent the columns. If an entry is `1` then a square will be drawn at that location on the grid. If an entry is `0` then the corresponding location on the grid will be empty. Thus, by mixing `1`s and `0`s it is possible to create many different grid-based arrangements. |
| choices | array of strings | `[['3','5','7','9']]` | The dimensions of this array must match the dimensions of `grid`. Each entry in this array is the key that should be pressed for that corresponding location in the grid. Entries can be left blank if there is no key associated with that location of the grid. |
| grid_square_size | numeric | 100 | The width and height in pixels of each square in the grid. |
| target_color | hex color code | `#999` | The color of the target square. |
| response_ends_trial | boolean | `true` | If true, the trial ends after a key press. Feedback is displayed if `show_response_feedback` is true. |
| pre_target_duration | numeric | 0 | The number of milliseconds to display the grid *before* the target changes color. |
| trial_duration | numeric | null | The maximum length of time of the trial, not including feedback. |
| show_response_feedback | boolean | false | If true, show feedback indicating where the user responded and whether it was correct. |
| feedback_duration | numeric | 200 | The length of time in milliseconds to show the feedback. |
| fade_duration | numeric | null | If a positive number, the target will progressively change color at the start of the trial, with the transition lasting this many milliseconds. |
| prompt | string | null | This string can contain HTML markup. Any content here will be displayed below the stimulus. The intention is that it can be used to provide a reminder about the action the subject is supposed to take (e.g., which keys to press). |
## Data Generated
In addition to the [default data collected by all plugins](overview#datacollectedbyplugins), this plugin collects the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
grid | JSON | A JSON-encoded representation of the grid.
target | JSON | A JSON-encoded representation of the target on the grid.
key_press | numeric | Indicates which key the subject pressed. The value is the [numeric key code](http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes) corresponding to the subject's response.
rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the second stimulus first appears on the screen until the subject's response.
correct | boolean | `true` if the subject's response matched the target.
| Name | Type | Value |
| --------- | ------- | ---------------------------------------- |
| grid | array | The representation of the grid. This will be encoded as a JSON string when data is saved using the `.json()` or `.csv()` functions. |
| target | array | The representation of the target location on the grid. This will be encoded as a JSON string when data is saved using the `.json()` or `.csv()` functions. |
| response | string | Indicates which key the subject pressed. |
| rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the second stimulus first appears on the screen until the subject's response. |
| correct | boolean | `true` if the subject's response matched the target. |
## Examples

View File

@ -4,7 +4,7 @@ The survey-html-form plugin displays a set of `<inputs>` from a HTML string. The
## Parameters
Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
@ -12,15 +12,17 @@ html | string | *undefined* | HTML formatted string containing all the input ele
preamble | string | empty string | HTML formatted string to display at the top of the page above all the questions.
button_label | string | 'Continue' | The text that appears on the button to finish the trial.
dataAsArray | boolean | false | Retrieve the data as an array e.g. [{name: "INPUT_NAME", value: "INPUT_VALUE"}, ...] instead of an object e.g. {INPUT_NAME: INPUT_VALUE, ...}. This might be useful if you omit naming your inputs.
autofocus | string | empty string | The HTML element ID of a form field to autofocus on. The focused element is the element that will receive keyboard events. For elements like `<input type="text">` or `<textbox>`, autofocus means that the cursor will appear in the text input area when the trial loads.
autocomplete | boolean | false | This determines whether or not all of the input elements on the page should allow autocomplete. Setting this to true will enable autocomplete or auto-fill for the form.
## Data Generated
In addition to the [default data collected by all plugins](overview#datacollectedbyplugins), this plugin collects the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
responses | string | A JS object encoded in JSON format containing the response for each input. The encoded object will have a separate variable for the response to each input, with each variable being named after its corresponding input element. Each response is a string containing whatever the subject answered for this particular input.
rt | numeric | The response time in milliseconds for the subject to make a response.
response | object | An object containing the response for each input. The object will have a separate key (variable) for the response to each input, with each variable being named after its corresponding input element. Each response is a string containing whatever the subject answered for this particular input. This will be encoded as a JSON string when data is saved using the `.json()` or `.csv()` functions. |
rt | numeric | The response time in milliseconds for the subject to make a response. |
## Examples
@ -33,3 +35,16 @@ var form_trial = {
html: '<p> I am feeling <input name="first" type="text" />, <input name="second" type="text" />, and <input name="third" type="text" />.</p>'
};
```
### Example using the autofocus parameter
In this example, the browser will focus on the element with the ID `test-resp-box` when the trial loads. For `<input type="text">` elements, this means that the cursor will appear inside the text box.
```javascript
var autofocus_trial = {
type: 'survey-html-form',
preamble: '<p> What is your favorite bird?</p>',
html: '<p>My favorite bird is <input type="text" id="test-resp-box" name="response" size="10" /></p>',
autofocus: 'test-resp-box'
};
```

View File

@ -4,7 +4,7 @@ The survey-likert plugin displays a set of questions with Likert scale responses
## Parameters
Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
@ -13,16 +13,17 @@ randomize_question_order | boolean | `false` | If true, the display order of `qu
preamble | string | empty string | HTML formatted string to display at the top of the page above all the questions.
scale_width | numeric | null | The width of the likert scale in pixels. If left `null`, then the width of the scale will be equal to the width of the widest content on the page.
button_label | string | 'Continue' | Label of the button.
autocomplete | boolean | false | This determines whether or not all of the input elements on the page should allow autocomplete. Setting this to true will enable autocomplete or auto-fill for the form.
## Data Generated
In addition to the [default data collected by all plugins](overview#datacollectedbyplugins), this plugin collects the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
responses | JSON string | A string in JSON format containing the response for each question. The encoded object will have a separate variable for the response to each question, with the first question in the trial being recorded in `Q0`, the second in `Q1`, and so on. The responses are recorded as integers, representing the position of the slider on the scale. If the `name` parameter is defined for the question, then the response will use the value of `name` as the key for the response in the `responses` object.
rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the questions first appear on the screen until the subject's response.
question_order | JSON string | A string in JSON format containing an array with the order of questions. For example `[2,0,1]` would indicate that the first question was `trial.questions[2]` (the third item in the `questions` parameter), the second question was `trial.questions[0]`, and the final question was `trial.questions[1]`.
response | object | An object containing the response for each question. The object will have a separate key (variable) for each question, with the first question in the trial being recorded in `Q0`, the second in `Q1`, and so on. The responses are recorded as integers, representing the position selected on the likert scale for that question. If the `name` parameter is defined for the question, then the response object will use the value of `name` as the key for each question. This will be encoded as a JSON string when data is saved using the `.json()` or `.csv()` functions. |
rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the questions first appear on the screen until the subject's response(s) are submitted. |
question_order | array | An array with the order of questions. For example `[2,0,1]` would indicate that the first question was `trial.questions[2]` (the third item in the `questions` parameter), the second question was `trial.questions[0]`, and the final question was `trial.questions[1]`. This will be encoded as a JSON string when data is saved using the `.json()` or `.csv()` functions. |
## Examples

View File

@ -4,7 +4,7 @@ The survey-multi-choice plugin displays a set of questions with multiple choice
## Parameters
Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
@ -12,16 +12,17 @@ questions | array | *undefined* | An array of objects, each object represents a
randomize_question_order | boolean | `false` | If true, the display order of `questions` is randomly determined at the start of the trial. In the data object, `Q0` will still refer to the first question in the array, regardless of where it was presented visually.
preamble | string | empty string | HTML formatted string to display at the top of the page above all the questions.
button_label | string | 'Continue' | Label of the button.
autocomplete | boolean | false | This determines whether or not all of the input elements on the page should allow autocomplete. Setting this to true will enable autocomplete or auto-fill for the form.
## Data Generated
In addition to the [default data collected by all plugins](overview#datacollectedbyplugins), this plugin collects the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
responses | JSON string | A string in JSON format containing the response for each question. The encoded object will have a separate variable for the response to each question, with the first question in the trial being recorded in `Q0`, the second in `Q1`, and so on. The responses are recorded as the name of the option label. If the `name` parameter is defined for the question, then the response will use the value of `name` as the key for the response in the `responses` object.
rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the questions first appear on the screen until the subject's response.
question_order | JSON string | A string in JSON format containing an array with the order of questions. For example `[2,0,1]` would indicate that the first question was `trial.questions[2]` (the third item in the `questions` parameter), the second question was `trial.questions[0]`, and the final question was `trial.questions[1]`.
response | object | An object containing the response for each question. The object will have a separate key (variable) for each question, with the first question in the trial being recorded in `Q0`, the second in `Q1`, and so on. The responses are recorded as the name of the option label selected (string). If the `name` parameter is defined for the question, then the response object will use the value of `name` as the key for each question. This will be encoded as a JSON string when data is saved using the `.json()` or `.csv()` functions. |
rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the questions first appear on the screen until the subject's response(s) are submitted. |
question_order | array | An array with the order of questions. For example `[2,0,1]` would indicate that the first question was `trial.questions[2]` (the third item in the `questions` parameter), the second question was `trial.questions[0]`, and the final question was `trial.questions[1]`. This will be encoded as a JSON string when data is saved using the `.json()` or `.csv()` functions. |
## Examples

View File

@ -4,7 +4,7 @@ The survey-multi-select plugin displays a set of questions with multiple select
## Parameters
Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
@ -13,16 +13,17 @@ randomize_question_order | boolean | `false` | If true, the display order of `qu
preamble | string | empty string | HTML formatted string to display at the top of the page above all the questions.
button_label | string | 'Continue' | Label of the button.
required_message | string | 'You must choose at least one response for this question' | Message to display if required response is not given.
autocomplete | boolean | false | This determines whether or not all of the input elements on the page should allow autocomplete. Setting this to true will enable autocomplete or auto-fill for the form.
## Data Generated
In addition to the [default data collected by all plugins](overview#datacollectedbyplugins), this plugin collects the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
responses | JSON string | An array containing all selected choices in JSON format for each question. The encoded object will have a separate variable for the response to each question, with the first question in the trial being recorded in `Q0`, the second in `Q1`, and so on. The responses are recorded as the name of the option label. If the `name` parameter is defined for the question, then the response will use the value of `name` as the key for the response in the `responses` object.
rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the questions first appear on the screen until the subject's response.
question_order | JSON string | A string in JSON format containing an array with the order of questions. For example `[2,0,1]` would indicate that the first question was `trial.questions[2]` (the third item in the `questions` parameter), the second question was `trial.questions[0]`, and the final question was `trial.questions[1]`.
response | object | An object containing the response for each question. The object will have a separate key (variable) for each question, with the first question in the trial being recorded in `Q0`, the second in `Q1`, and so on. For each question, the responses are recorded as arrays containing any response options that were selected (strings). If the `name` parameter is defined for the question, then the response object will use the value of `name` as the key for each question. This will be encoded as a JSON string when data is saved using the `.json()` or `.csv()` functions. |
rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the questions first appear on the screen until the subject's response(s) were submitted. |
question_order | array | An array with the order of questions. For example `[2,0,1]` would indicate that the first question was `trial.questions[2]` (the third item in the `questions` parameter), the second question was `trial.questions[0]`, and the final question was `trial.questions[1]`. This will be encoded as a JSON string when data is saved using the `.json()` or `.csv()` functions. |
## Examples

View File

@ -4,7 +4,7 @@ The survey-text plugin displays a set of questions with free response text field
## Parameters
Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
@ -12,16 +12,17 @@ questions | array | *undefined* | An array of objects, each object represents a
randomize_question_order | boolean | `false` | If true, the display order of `questions` is randomly determined at the start of the trial. In the data object, `Q0` will still refer to the first question in the array, regardless of where it was presented visually.
preamble | string | empty string | HTML formatted string to display at the top of the page above all the questions.
button_label | string | 'Continue' | The text that appears on the button to finish the trial.
autocomplete | boolean | false | This determines whether or not all of the input elements on the page should allow autocomplete. Setting this to true will enable autocomplete or auto-fill for the form.
## Data Generated
In addition to the [default data collected by all plugins](overview#datacollectedbyplugins), this plugin collects the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
responses | JSON string | A string in JSON format containing the response for each question. The encoded object will have a separate variable for the response to each question, with the first question in the trial being recorded in `Q0`, the second in `Q1`, and so on. Each response is a string containing whatever the subject typed into the associated text box. If the `name` parameter is defined for the question, then the response will use the value of `name` as the key for the response in the `responses` object.
rt | numeric | The response time in milliseconds for the subject to make a response.
question_order | JSON string | A string in JSON format containing an array with the order of questions. For example `[2,0,1]` would indicate that the first question was `trial.questions[2]` (the third item in the `questions` parameter), the second question was `trial.questions[0]`, and the final question was `trial.questions[1]`.
response | object | An object containing the response for each question. The object will have a separate key (variable) for each question, with the first question in the trial being recorded in `Q0`, the second in `Q1`, and so on. For each question, the response is a string containing whatever text was in the response box when the responses were submitted. If the `name` parameter is defined for the question, then the response object will use the value of `name` as the key for each question. This will be encoded as a JSON string when data is saved using the `.json()` or `.csv()` functions. |
rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the questions first appear on the screen until the subject's response(s) were submitted. |
question_order | array | An array with the order of questions. For example `[2,0,1]` would indicate that the first question was `trial.questions[2]` (the third item in the `questions` parameter), the second question was `trial.questions[0]`, and the final question was `trial.questions[1]`. This will be encoded as a JSON string when data is saved using the `.json()` or `.csv()` functions. |
## Examples

View File

@ -1,15 +1,17 @@
# jspsych-video-button-response plugin
This plugin plays a video and records responses generated by button click. The stimulus can be displayed until a response is given, or for a pre-determined amount of time. The trial can be ended automatically if the subject has failed to respond within a fixed length of time. The button itself can be customized using HTML formatting.
This plugin plays a video and records responses generated by button click. The stimulus can be displayed until a response is given, or for a pre-determined amount of time. The trial can be ended automatically when the subject responds, when the video file has finished playing, or if the subject has failed to respond within a fixed length of time. You can also prevent a button response from being made before the video has finished playing. The button itself can be customized using HTML formatting.
Video files can be automatically preloaded by jsPsych using the [`preload` plugin](jspsych-preload.md). However, if you are using timeline variables or another dynamic method to specify the video stimulus, you will need to [manually preload](/overview/media-preloading/#manual-preloading) the videos. Also note that video preloading is disabled when the experiment is running as a file (i.e. opened directly in the browser, rather than through a server), in order to prevent CORS errors - see the section on [Running Experiments](/overview/running-experiments.md) for more information.
## Parameters
Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
sources | array | *undefined* | An array of file paths to the video. You can specify multiple formats of the same video (e.g., .mp4, .ogg, .webm) to maximize the [cross-browser compatibility](https://developer.mozilla.org/en-US/docs/Web/HTML/Supported_media_formats). Usually .mp4 is a safe cross-browser option. The player will use the first source file in the array that is compatible with the browser, so specify the files in order of preference.
choices | array of strings | [] | Labels for the buttons. Each different string in the array will generate a different button.
stimulus | array | *undefined* | An array of file paths to the video. You can specify multiple formats of the same video (e.g., .mp4, .ogg, .webm) to maximize the [cross-browser compatibility](https://developer.mozilla.org/en-US/docs/Web/HTML/Supported_media_formats). Usually .mp4 is a safe cross-browser option. The plugin does not reliably support .mov files. The player will use the first source file in the array that is compatible with the browser, so specify the files in order of preference.
choices | array of strings | *undefined* | Labels for the buttons. Each different string in the array will generate a different button.
button_html | HTML string | `'<button class="jspsych-btn">%choice%</button>'` | A template of HTML for generating the button elements. You can override this to create customized buttons of various kinds. The string `%choice%` will be changed to the corresponding element of the `choices` array. You may also specify an array of strings, if you need different HTML to render for each button. If you do specify an array, the `choices` array and this array must have the same length. The HTML from position 0 in the `button_html` array will be used to create the button for element 0 in the `choices` array, and so on.
margin_vertical | string | '0px' | Vertical margin of the button(s).
margin_horizontal | string | '8px' | Horizontal margin of the button(s).
@ -23,25 +25,26 @@ stop| numeric | null | If given a value, the video will stop at this time point
rate | numeric | null | The playback rate of the video. 1 is normal, <1 is slower, >1 is faster.
trial_ends_after_video | bool | false | If true, then the trial will end as soon as the video file finishes playing.
trial_duration | numeric | null | How long to wait for the subject to make a response before ending the trial in milliseconds. If the subject fails to make a response before this timer is reached, the subject's response will be recorded as null for the trial and the trial will end. If the value of this parameter is null, then the trial will wait for a response indefinitely.
response_ends_trial | boolean | true | If true, then the trial will end whenever the subject makes a response (assuming they make their response before the cutoff specified by the `timing_response` parameter). If false, then the trial will continue until the value for `trial_duration` is reached. You can use this parameter to force the subject to view a stimulus for a fixed amount of time, even if they respond before the time is complete.
response_ends_trial | boolean | true | If true, then the trial will end whenever the subject makes a response (assuming they make their response before the cutoff specified by the `trial_duration` parameter). If false, then the trial will continue until the value for `trial_duration` is reached. You can set this parameter to `false` to force the subject to view a stimulus for a fixed amount of time, even if they respond before the time is complete.
response_allowed_while_playing | boolean | true | If true, then responses are allowed while the video is playing. If false, then the video must finish playing before the button choices are enabled and a response is accepted. Once the video has played all the way through, the buttons are enabled and a response is allowed (including while the video is being re-played via on-screen playback controls).
## Data Generated
In addition to the [default data collected by all plugins](overview#datacollectedbyplugins), this plugin collects the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
button_pressed | numeric | Indicates which button the subject pressed. The first button in the `choices` array is 0, the second is 1, and so on.
rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the stimulus first appears on the screen until the subject's response.
stimulus | string | JSON encoding of the `sources` array.
response | numeric | Indicates which button the subject pressed. The first button in the `choices` array is 0, the second is 1, and so on.
rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the stimulus first appears on the screen until the subject's response.
stimulus | array | The `stimulus` array. This will be encoded as a JSON string when data is saved using the `.json()` or `.csv()` functions.
## Example
```javascript
var trial = {
type: 'video-keyboard-response',
sources: [
type: 'video-button-response',
stimulus: [
'video/sample_video.mp4',
'video/sample_video.ogg'
],

View File

@ -1,44 +1,46 @@
# jspsych-video-keyboard-response plugin
This plugin plays a video file and records a keyboard response. Various aspects of the timing, video playback, and keyboard options can be controlled through parameters.
This plugin plays a video file and records a keyboard response. The stimulus can be displayed until a response is given, or for a pre-determined amount of time. The trial can be ended automatically when the subject responds, when the video file has finished playing, or if the subject has failed to respond within a fixed length of time. You can also prevent a keyboard response from being recorded before the video has finished playing.
Video files can be automatically preloaded by jsPsych using the [`preload` plugin](jspsych-preload.md). However, if you are using timeline variables or another dynamic method to specify the video stimulus, you will need to [manually preload](/overview/media-preloading/#manual-preloading) the videos. Also note that video preloading is disabled when the experiment is running as a file (i.e. opened directly in the browser, rather than through a server), in order to prevent CORS errors - see the section on [Running Experiments](/overview/running-experiments.md) for more information.
## Parameters
Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
sources | array | *undefined* | An array of file paths to the video. You can specify multiple formats of the same video (e.g., .mp4, .ogg, .webm) to maximize the [cross-browser compatibility](https://developer.mozilla.org/en-US/docs/Web/HTML/Supported_media_formats). Usually .mp4 is a safe cross-browser option. The player will use the first source file in the array that is compatible with the browser, so specify the files in order of preference.
prompt | string | null | This string can contain HTML markup. Any content here will be displayed below the stimulus. The intention is that it can be used to provide a reminder about the action the subject is supposed to take (e.g., which key to press).
width | numeric | width of the video file | The width of the video display in pixels.
height | numeric | heigh of the video file | The height of the video display in pixels.
autoplay | boolean | true | If true, the video will begin playing as soon as it has loaded.
controls | boolean | false | If true, controls for the video player will be available to the subject. They will be able to pause the video or move the playback to any point in the video.
start | numeric | null | If given a value, the video will start at this time point in seconds.
stop| numeric | null | If given a value, the video will stop at this time point in seconds.
rate | numeric | null | The playback rate of the video. 1 is normal, <1 is slower, >1 is faster.
choices | array of keycodes | `jsPsych.ALL_KEYS` | This array contains the keys that the subject is allowed to press in order to respond to the stimulus. Keys can be specified as their [numeric key code](http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes) or as characters (e.g., `'a'`, `'q'`). The default value of `jsPsych.ALL_KEYS` means that all keys will be accepted as valid responses. Specifying `jsPsych.NO_KEYS` will mean that no responses are allowed.
trial_ends_after_video | bool | false | If true, then the trial will end as soon as the video file finishes playing.
trial_duration | numeric | null | How long to wait for the subject to make a response before ending the trial in milliseconds. If the subject fails to make a response before this timer is reached, the subject's response will be recorded as null for the trial and the trial will end. If the value of this parameter is null, then the trial will wait for a response indefinitely.
response_ends_trial | boolean | true | If true, then the trial will end whenever the subject makes a response (assuming they make their response before the cutoff specified by the `timing_response` parameter). If false, then the trial will continue until the value for `trial_duration` is reached. You can use this parameter to force the subject to view a stimulus for a fixed amount of time, even if they respond before the time is complete.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
| Parameter | Type | Default Value | Description |
| ------------------------------ | ---------------- | ----------------------- | ---------------------------------------- |
| stimulus | array | *undefined* | An array of file paths to the video. You can specify multiple formats of the same video (e.g., .mp4, .ogg, .webm) to maximize the [cross-browser compatibility](https://developer.mozilla.org/en-US/docs/Web/HTML/Supported_media_formats). Usually .mp4 is a safe cross-browser option. The plugin does not reliably support .mov files. The player will use the first source file in the array that is compatible with the browser, so specify the files in order of preference. |
| prompt | string | null | This string can contain HTML markup. Any content here will be displayed below the stimulus. The intention is that it can be used to provide a reminder about the action the subject is supposed to take (e.g., which key to press). |
| width | numeric | width of the video file | The width of the video display in pixels. |
| height | numeric | heigh of the video file | The height of the video display in pixels. |
| autoplay | boolean | true | If true, the video will begin playing as soon as it has loaded. |
| controls | boolean | false | If true, controls for the video player will be available to the subject. They will be able to pause the video or move the playback to any point in the video. |
| start | numeric | null | If given a value, the video will start at this time point in seconds. |
| stop | numeric | null | If given a value, the video will stop at this time point in seconds. |
| rate | numeric | null | The playback rate of the video. 1 is normal, <1 is slower, >1 is faster. |
| choices | array of strings | `jsPsych.ALL_KEYS` | This array contains the key(s) that the subject is allowed to press in order to respond to the stimulus. Keys should be specified as characters (e.g., `'a'`, `'q'`, `' '`, `'Enter'`, `'ArrowDown'`) - see [this page](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values) and [this page (event.key column)](https://www.freecodecamp.org/news/javascript-keycode-list-keypress-event-key-codes/) for more examples. Any key presses that are not listed in the array will be ignored. The default value of `jsPsych.ALL_KEYS` means that all keys will be accepted as valid responses. Specifying `jsPsych.NO_KEYS` will mean that no responses are allowed. |
| trial_ends_after_video | bool | false | If true, then the trial will end as soon as the video file finishes playing. |
| trial_duration | numeric | null | How long to wait for the subject to make a response before ending the trial in milliseconds. If the subject fails to make a response before this timer is reached, the subject's response will be recorded as null for the trial and the trial will end. If the value of this parameter is null, then the trial will wait for a response indefinitely. |
| response_ends_trial | boolean | true | If true, then the trial will end whenever the subject makes a response (assuming they make their response before the cutoff specified by the `trial_duration` parameter). If false, then the trial will continue until the value for `trial_duration` is reached. You can set this parameter to `false` to force the subject to view a stimulus for a fixed amount of time, even if they respond before the time is complete. |
| response_allowed_while_playing | boolean | true | If true, then responses are allowed while the video is playing. If false, then the video must finish playing before a keyboard response is accepted. Once the video has played all the way through, a valid keyboard response is allowed (including while the video is being re-played via on-screen playback controls). |
## Data Generated
In addition to the [default data collected by all plugins](overview#datacollectedbyplugins), this plugin collects the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
key_press | numeric | Indicates which key the subject pressed. The value is the [numeric key code](http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes) corresponding to the subject's response.
rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the stimulus first appears on the screen until the subject's response.
stimulus | string | JSON encoding of the `sources` array.
| Name | Type | Value |
| --------- | ------- | ---------------------------------------- |
| response | string | Indicates which key the subject pressed. |
| rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the stimulus first appears on the screen until the subject's response. |
stimulus | array | The `stimulus` array. This will be encoded as a JSON string when data is saved using the `.json()` or `.csv()` functions. |
## Example
```javascript
var trial = {
type: 'video-keyboard-response',
sources: [
stimulus: [
'video/sample_video.mp4',
'video/sample_video.ogg'
],

View File

@ -1,14 +1,16 @@
# jspsych-video-slider-response plugin
This plugin plays a video and allows the subject to respond by dragging a slider.
This plugin plays a video and allows the subject to respond by dragging a slider. The stimulus can be displayed until a response is given, or for a pre-determined amount of time. The trial can be ended automatically when the subject responds, when the video file has finished playing, or if the subject has failed to respond within a fixed length of time. You can also prevent the slider response from being made before the video has finished playing.
Video files can be automatically preloaded by jsPsych using the [`preload` plugin](jspsych-preload.md). However, if you are using timeline variables or another dynamic method to specify the video stimulus, you will need to [manually preload](/overview/media-preloading/#manual-preloading) the videos. Also note that video preloading is disabled when the experiment is running as a file (i.e. opened directly in the browser, rather than through a server), in order to prevent CORS errors - see the section on [Running Experiments](/overview/running-experiments.md) for more information.
## Parameters
Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
sources | array | *undefined* | An array of file paths to the video. You can specify multiple formats of the same video (e.g., .mp4, .ogg, .webm) to maximize the [cross-browser compatibility](https://developer.mozilla.org/en-US/docs/Web/HTML/Supported_media_formats). Usually .mp4 is a safe cross-browser option. The player will use the first source file in the array that is compatible with the browser, so specify the files in order of preference.
stimulus | array | *undefined* | An array of file paths to the video. You can specify multiple formats of the same video (e.g., .mp4, .ogg, .webm) to maximize the [cross-browser compatibility](https://developer.mozilla.org/en-US/docs/Web/HTML/Supported_media_formats). Usually .mp4 is a safe cross-browser option. The plugin does not reliably support .mov files. The player will use the first source file in the array that is compatible with the browser, so specify the files in order of preference.
prompt | string | null | This string can contain HTML markup. Any content here will be displayed below the stimulus. The intention is that it can be used to provide a reminder about the action the subject is supposed to take (e.g., which key to press).
width | numeric | width of the video file | The width of the video display in pixels.
height | numeric | heigh of the video file | The height of the video display in pixels.
@ -21,30 +23,34 @@ min | integer | 0 | Sets the minimum value of the slider.
max | integer | 100 | Sets the maximum value of the slider.
slider_start | integer | 50 | Sets the starting value of the slider
step | integer | 1 | Sets the step of the slider. This is the smallest amount by which the slider can change.
labels | array of strings | [] | Labels displayed at equidistant locations on the slider. For example, two labels will be placed at the ends of the slider. Three labels would place two at the ends and one in the middle. Four will place two at the ends, and the other two will be at 33% and 67% of the slider width.
slider_width | integer | null | Set the width of the slider in pixels. If left null, then the width will be equal to the widest element in the display.
require_movement | boolean | false | If true, the subject must move the slider before clicking the continue button.
button_label | string | 'Continue' | Label of the button to end the trial.
trial_ends_after_video | bool | false | If true, then the trial will end as soon as the video file finishes playing.
trial_duration | numeric | null | How long to wait for the subject to make a response before ending the trial in milliseconds. If the subject fails to make a response before this timer is reached, the subject's response will be recorded as null for the trial and the trial will end. If the value of this parameter is null, then the trial will wait for a response indefinitely.
response_ends_trial | boolean | true | If true, then the trial will end whenever the subject makes a response (assuming they make their response before the cutoff specified by the `timing_response` parameter). If false, then the trial will continue until the value for `trial_duration` is reached. You can use this parameter to force the subject to view a stimulus for a fixed amount of time, even if they respond before the time is complete.
response_ends_trial | boolean | true | If true, then the trial will end whenever the subject makes a response (assuming they make their response before the cutoff specified by the `trial_duration` parameter). If false, then the trial will continue until the value for `trial_duration` is reached. You can set this parameter to `false` to force the subject to view a stimulus for a fixed amount of time, even if they respond before the time is complete.
response_allowed_while_playing | boolean | true | If true, then responses are allowed while the video is playing. If false, then the video must finish playing before the slider is enabled and the trial can end via the next button click. Once the video has played all the way through, the slider is enabled and a response is allowed (including while the video is being re-played via on-screen playback controls).
## Data Generated
In addition to the [default data collected by all plugins](overview#datacollectedbyplugins), this plugin collects the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
response | numeric | The numeric value of the slider.
rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the stimulus first appears on the screen until the subject's response.
stimulus | string | JSON encoding of the `sources` array.
stimulus | array | The `stimulus` array. This will be encoded as a JSON string when data is saved using the `.json()` or `.csv()` functions.
slider_start | numeric | The starting value of the slider.
start | numeric | The start time of the video clip.
## Example
```javascript
var trial = {
type: 'video-slider-response',
sources: [
stimulus: [
'video/sample_video.mp4',
'video/sample_video.ogg'
],

View File

@ -6,35 +6,35 @@ This plugin presents a customizable visual-search task modelled after [Wang, Cav
## Parameters
Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
target_present | boolean | *undefined* | Is the target present?
set_size | numeric | *undefined* | How many items should be displayed?
target | string | *undefined* | Path to image file that is the search target.
foil | string or array | *undefined* | Path to image file that is the foil/distractor. Can specify an array of distractors if the distractors are all different images.
fixation_image | string | *undefined* | Path to image file that is a fixation target.
target_size | array | `[50, 50]` | Two element array indicating the height and width of the search array element images.
fixation_size | array | `[16, 16]` | Two element array indicating the height and width of the fixation image.
circle_diameter | numeric | 250 | The diameter of the search array circle in pixels.
target_present_key | numeric | 74 | The key to press if the target is present in the search array.
target_absent_key | numeric | 70 | The key to press if the target is not present in the search array.
trial_duration | numeric | null | The maximum amount of time the subject is allowed to search before the trial will continue. A value of null will allow the subject to search indefinitely.
fixation_duration | numeric | 1000 | How long to show the fixation image for before the search array (in milliseconds).
| Parameter | Type | Default Value | Description |
| ------------------ | --------------- | ------------- | ---------------------------------------- |
| target_present | boolean | *undefined* | Is the target present? |
| set_size | numeric | *undefined* | How many items should be displayed? |
| target | string | *undefined* | Path to image file that is the search target. |
| foil | string or array | *undefined* | Path to image file that is the foil/distractor. Can specify an array of distractors if the distractors are all different images. |
| fixation_image | string | *undefined* | Path to image file that is a fixation target. |
| target_size | array | `[50, 50]` | Two element array indicating the height and width of the search array element images. |
| fixation_size | array | `[16, 16]` | Two element array indicating the height and width of the fixation image. |
| circle_diameter | numeric | 250 | The diameter of the search array circle in pixels. |
| target_present_key | string | 'j' | The key to press if the target is present in the search array. |
| target_absent_key | string | 'f' | The key to press if the target is not present in the search array. |
| trial_duration | numeric | null | The maximum amount of time the subject is allowed to search before the trial will continue. A value of null will allow the subject to search indefinitely. |
| fixation_duration | numeric | 1000 | How long to show the fixation image for before the search array (in milliseconds). |
## Data Generated
In addition to the [default data collected by all plugins](overview#datacollectedbyplugins), this plugin collects the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
correct | boolean | True if the subject gave the correct response.
key_press | numeric | Indicates which key the subject pressed. The value is the [numeric key code](http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes) corresponding to the subject's response.
rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the stimulus first appears on the screen until the subject's response.
set_size | numeric | The number of items in the search array
target_present | boolean | True if the target is present in the search array
locations | JSON string | JSON-encoded array where each element of the array is the pixel value of the center of an image in the search array. If the target is present, then the first element will represent the location of the target.
| Name | Type | Value |
| -------------- | ----------- | ---------------------------------------- |
| correct | boolean | True if the subject gave the correct response. |
| response | string | Indicates which key the subject pressed. |
| rt | numeric | The response time in milliseconds for the subject to make a response. The time is measured from when the stimulus first appears on the screen until the subject's response. |
| set_size | numeric | The number of items in the search array |
| target_present | boolean | True if the target is present in the search array |
| locations | array | Array where each element is the pixel value of the center of an image in the search array. If the target is present, then the first element will represent the location of the target. This will be encoded as a JSON string when data is saved using the `.json()` or `.csv()` functions. |
## Example

View File

@ -10,27 +10,27 @@ This plugin requires the Snap.svg library, available at [http://www.snapsvg.io](
## Parameters
Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
stimuli | array | *undefined* | Each element of the array is a stimulus. A stimulus is a path to an image file. The order of stimuli in the array determines the order of the animation sequence.
canvas_size | array | `[400, 400]` | Array specifying the width and height of the area that the animation will display in. Stimuli will move to the edges of this area, so increasing the width without increasing the `timing_cycle` parameter will speed up the images.
image_size | array | `[100, 100]` | Array specifying the width and height of the images to show. The occluding rectangle will have a width equal to the width of image_size.
initial_direction | string | "left" | Which direction the stimulus should move first (subsequent directions will alternate). Choices are "left" or "right".
occlude_center | boolean | true | If true, display a rectangle in the center of the screen that is just wide enough to occlude the image completely as it passes behind.
choices | array of keycodes | `jsPsych.ALL_KEYS` | This array contains the keys that the subject is allowed to press in order to respond to the stimulus. Keys can be specified as their [numeric key code](http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes) or as characters (e.g., `'a'`, `'q'`). The default value of `jsPsych.ALL_KEYS` means that all keys will be accepted as valid responses. Specifying `jsPsych.NO_KEYS` will mean that no responses are allowed.
cycle_duration | numeric | 1000 | How long it takes for a stimulus in the sequence to make a complete cycle (move to the edge and back to the center) in milliseconds.
pre_movement_duration | numeric | 500 | How long to wait before the stimuli starts moving from behind the center rectangle.
| Parameter | Type | Default Value | Description |
| --------------------- | ---------------- | ------------------ | ---------------------------------------- |
| stimuli | array | *undefined* | Each element of the array is a stimulus. A stimulus is a path to an image file. The order of stimuli in the array determines the order of the animation sequence. |
| canvas_size | array | `[400, 400]` | Array specifying the width and height of the area that the animation will display in. Stimuli will move to the edges of this area, so increasing the width without increasing the `timing_cycle` parameter will speed up the images. |
| image_size | array | `[100, 100]` | Array specifying the width and height of the images to show. The occluding rectangle will have a width equal to the width of image_size. |
| initial_direction | string | "left" | Which direction the stimulus should move first (subsequent directions will alternate). Choices are "left" or "right". |
| occlude_center | boolean | true | If true, display a rectangle in the center of the screen that is just wide enough to occlude the image completely as it passes behind. |
| choices | array of strings | `jsPsych.ALL_KEYS` | This array contains the key(s) that the subject is allowed to press in order to respond to the stimulus. Keys should be specified as characters (e.g., `'a'`, `'q'`, `' '`, `'Enter'`, `'ArrowDown'`) - see [this page](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values) and [this page (event.key column)](https://www.freecodecamp.org/news/javascript-keycode-list-keypress-event-key-codes/) for more examples. Any key presses that are not listed in the array will be ignored. The default value of `jsPsych.ALL_KEYS` means that all keys will be accepted as valid responses. Specifying `jsPsych.NO_KEYS` will mean that no responses are allowed. |
| cycle_duration | numeric | 1000 | How long it takes for a stimulus in the sequence to make a complete cycle (move to the edge and back to the center) in milliseconds. |
| pre_movement_duration | numeric | 500 | How long to wait before the stimuli starts moving from behind the center rectangle. |
## Data Generated
In addition to the [default data collected by all plugins](overview#datacollectedbyplugins), this plugin collects the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
stimulus | JSON string | A JSON encoded array where each element of the array is a stimulus from the sequence, in the order that they were shown.
responses | JSON string | A JSON encoded array containing all response information. The encoded object is an array containing one element for each valid response. Each response item has three properties: `key` the key code of the response key, `stimulus` the index of the stimulus that was displayed when the response was made, and `rt` the response time measured since the start of the sequence.
| Name | Type | Value |
| --------- | ----------- | ---------------------------------------- |
| stimulus | array | Array where each element is a stimulus from the sequence, in the order that they were shown. This will be encoded as a JSON string when data is saved using the `.json()` or `.csv()` functions. |
| response | array | Array containing all response information. Each element in the array is an object representing each valid response. Each response item has three properties: `key` the key that was pressed, `stimulus` the index of the stimulus that was displayed when the response was made, and `rt` the response time measured since the start of the sequence. This will be encoded as a JSON string when data is saved using the `.json()` or `.csv()` functions. |
## Examples

View File

@ -6,21 +6,21 @@ Fiser, J., & Aslin, R. N. (2001). Unsupervised statistical learning of higher-or
## Parameters
Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
In addition to the [parameters available in all plugins](/overview/plugins#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
stimuli | array | *undefined* | An array that defines a grid. Grids should be declared as two dimensional arrays in `[row][col]` order, with paths to image files in the locations where images are displayed, and 0 in blank spaces. See example below.
image_size | array | `[100, 100]` | Array specifying the width and height of the images to show. Grid cells will also be this size, with 10% padding.
timing_duration | numeric | 2000 | How long to show the stimulus for in milliseconds.
| Parameter | Type | Default Value | Description |
| -------------- | ------- | ------------- | ---------------------------------------- |
| stimuli | array | *undefined* | An array that defines a grid. Grids should be declared as two dimensional arrays in `[row][col]` order, with paths to image files in the locations where images are displayed, and 0 in blank spaces. See example below. |
| image_size | array | `[100, 100]` | Array specifying the width and height of the images to show. Grid cells will also be this size, with 10% padding. |
| trial_duration | numeric | 2000 | How long to show the stimulus for in milliseconds. |
## Data Generated
In addition to the [default data collected by all plugins](overview#datacollectedbyplugins), this plugin collects the following data for each trial.
In addition to the [default data collected by all plugins](/overview/plugins#data-collected-by-all-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
stimulus | JSON string | JSON encoded array of the stimulus shown on the trial.
| Name | Type | Value |
| -------- | ----------- | ---------------------------------------- |
| stimulus | array | Two dimensional array representing the stimulus shown on the trial. This will be encoded as a JSON string when data is saved using the `.json()` or `.csv()` functions. |
### Stimulus Creation Method

View File

@ -0,0 +1,60 @@
# jspsych-webgazer-calibrate
This plugin can be used to calibrate the [WebGazer extension](/extensions/jspsych-ext-webgazer.md). For a narrative description of eye tracking with jsPsych, see the [eye tracking overview](/overview/eye-tracking.md).
## Parameters
In addition to the [parameters available in all plugins](overview.md#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
calibration_points | array | `[[10,10], [10,50], [10,90], [50,10], [50,50], [50,90], [90,10], [90,50], [90,90]]` | Array of points in `[x,y]` coordinates. Specified as a percentage of the screen width and height, from the left and top edge. The default grid is 9 points.
calibration_mode | string | `'click'` | Can specify `click` to have subjects click on calibration points or `view` to have subjects passively watch calibration points.
repetitions_per_point | numeric | 1 | The number of times to repeat the sequence of calibration points.
randomize_calibration_order | bool | `false` | Whether to randomize the order of the calibration points.
time_to_saccade | numeric | 1000 | If `calibration_mode` is set to `view`, then this is the delay before calibrating after showing a point. Gives the participant time to fixate on the new target before assuming that the participant is looking at the target.
time_per_point | numeric | 1000 | If `calibration_mode` is set to `view`, then this is the length of time to show a point while calibrating. Note that if `click` calibration is used then the point will remain on the screen until clicked.
## Data Generated
In addition to the [default data collected by all plugins](overview.md#data-collected-by-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
No data currently added by this plugin. Use the [webgazer-validate](/plugins/jspsych-webgazer-validate.md) plugin to measure the precision and accuracy of calibration.
## Example
#### Click-based calibration with 5 points
```javascript
var calibration = {
type: 'webgazer-calibrate',
calibration_points: [[50,50], [25,25], [25,75], [75,25], [75,75]],
repetitions_per_point: 2,
randomize_calibration_order: true
}
```
### View-based calibration with 33 points, concentrated in the center
```javascript
var calibration = {
type: 'webgazer-calibrate',
calibration_points: [
[10,10],[10,50],[10,90],
[30,10],[30,50],[30,90],
[40,10],[40,30],[40,40],[40,45],[40,50],[40,55],[40,60],[40,70],[40,90],
[50,10],[50,30],[50,40],[50,45],[50,50],[50,55],[50,60],[50,70],[50,90],
[60,10],[60,30],[60,40],[60,45],[60,50],[60,55],[60,60],[60,70],[60,90],
[70,10],[70,50],[70,90],
[90,10],[90,50],[90,90]
],
repetitions_per_point: 1,
randomize_calibration_order: true,
calibration_mode: 'view',
time_per_point: 500,
time_to_saccade: 1000
}
```

View File

@ -0,0 +1,31 @@
# jspsych-webgazer-init-camera
This plugin initializes the camera and helps the participant center their face in the camera view for using the the [WebGazer extension](/extensions/jspsych-ext-webgazer.md). For a narrative description of eye tracking with jsPsych, see the [eye tracking overview](/overview/eye-tracking.md).
## Parameters
In addition to the [parameters available in all plugins](overview.md#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
instructions | string | too long to put here | Instructions for the participant to follow.
button_text | string | Continue | The text for the button that participants click to end the trial.
## Data Generated
In addition to the [default data collected by all plugins](overview.md#data-collected-by-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
No additional data collected.
## Example
#### Parameterless use
```javascript
var init_camera = {
type: 'webgazer-init-camera'
}
```

View File

@ -0,0 +1,43 @@
# jspsych-webgazer-calibrate
This plugin can be used to measure the accuracy and precision of gaze predictions made by the [WebGazer extension](/extensions/jspsych-ext-webgazer.md). For a narrative description of eye tracking with jsPsych, see the [eye tracking overview](/overview/eye-tracking.md).
## Parameters
In addition to the [parameters available in all plugins](overview.md#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
validation_points | array | `[[10,10], [10,50], [10,90], [50,10], [50,50], [50,90], [90,10], [90,50], [90,90]]` | Array of points in `[x,y]` coordinates. The default grid is 9 points. Meaning of coordinates controlled by `validation_point_coordinates` parameter.
validation_point_coordinates | string | `'percent'` | Can specify `percent` to have validation point coordinates specified in percentage of screen width and height, or `center-offset-pixels` to specify each point as the distance in pixels from the center of the screen.
roi_radius | numeric | 200 | Tolerance around the validation point in pixels when calculating the percent of gaze measurements within the acceptable range.
repetitions_per_point | numeric | 1 | The number of times to repeat the sequence of calibration points.
randomize_validation_order | bool | `false` | Whether to randomize the order of the validation points.
time_to_saccade | numeric | 1000 | The delay before validating after showing a point. Gives the participant time to fixate on the new target before assuming that the participant is looking at the target.
validation_duration | numeric | 2000 | If `calibration_mode` is set to `view`, then this is the length of time to show a point while calibrating. Note that if `click` calibration is used then the point will remain on the screen until clicked.
point_size | numeric | 10 | Diameter of the validation points in pixels.
show_validation_data | bool | false | If `true` then a visualization of the validation data will be shown on the screen after the validation is complete. This will show each measured gaze location color coded by whether it is within the `roi_radius` of the target point. This is mainly intended for testing and debugging.
## Data Generated
In addition to the [default data collected by all plugins](overview.md#data-collected-by-plugins), this plugin collects the following data for each trial.
Name | Type | Value
-----|------|------
raw_gaze | array | Raw gaze data for the trial. The array will contain a nested array for each validation point. Within each nested array will be a list of `{dx,dy}` values specifying the distance from the target for that gaze point.
percent_in_roi | array | The percentage of samples within the `roi_radius` for each validation point.
average_offset | array | The average `x` and `y` distance from each validation point, plus the median distance `r` of the points from this average offset.
samples_per_sec | numeric | The average number of samples per second. Calculated by finding samples per second for each point and then averaging these estimates together.
## Example
#### 4 point validation using center offset mode
```javascript
var validation = {
type: 'webgazer-validate',
validation_points: [[-200,-200], [-200,200], [200,-200], [200,200]],
validation_point_coordinates: 'center-offset-pixels',
show_validation_data: true
}
```

View File

@ -0,0 +1,53 @@
# List of Plugins
These are the plugins that are included in the jsPsych release. If you don't see a plugin that will work for your needs, you can post on [GitHub Discussions](https://github.com/jspsych/jsPsych/discussions) to see if anyone else in the community has an unofficial plugin to share or to get help creating a new plugin. You can also view the [documentation on creating a new plugin](/overview/plugins/#creating-a-new-plugin) or [watch a video tutorial on creating a new plugin](https://www.youtube.com/watch?v=XQcsFwAmbiw&list=PLnfo1lBY1P2Mf_o6rV5wiqqn92Mw3UTGh&index=4).
Plugin | Description
------ | -----------
[jspsych&#8209;animation](/plugins/jspsych-animation) | Shows a sequence of images at a specified frame rate. Records key presses (including timing information) made by the subject while they are viewing the animation.
[jspsych&#8209;audio&#8209;button&#8209;response](/plugins/jspsych-audio-button-response) | Play an audio file and allow the subject to respond by choosing a button to click. The button can be customized extensively, e.g., using images in place of standard buttons.
[jspsych&#8209;audio&#8209;keyboard&#8209;response](/plugins/jspsych-audio-keyboard-response) | Play an audio file and allow the subject to respond by pressing a key.
[jspsych&#8209;audio&#8209;slider&#8209;response](/plugins/jspsych-audio-slider-response) | Play an audio file and allow the subject to respond by moving a slider to indicate a value.
[jspsych&#8209;call&#8209;function](/plugins/jspsych-call-function) | Executes an arbitrary function call. Doesn't display anything to the subject, and the subject is usually unaware that this plugin has even executed. It's useful for performing tasks at specified times in the experiment, such as saving data.
[jspsych&#8209;canvas&#8209;button&#8209;response](/plugins/jspsych-canvas-button-response) | Draw a stimulus on a [HTML canvas element](https://www.w3schools.com/html/html5_canvas.asp), and record a button click response. Useful for displaying dynamic, parametrically-defined graphics, and for controlling the positioning of multiple graphical elements (shapes, text, images).
[jspsych&#8209;canvas&#8209;keyboard&#8209;response](/plugins/jspsych-canvas-keyboard-response) | Draw a stimulus on a [HTML canvas element](https://www.w3schools.com/html/html5_canvas.asp), and record a key press response. Useful for displaying dynamic, parametrically-defined graphics, and for controlling the positioning of multiple graphical elements (shapes, text, images).
[jspsych&#8209;canvas&#8209;slider&#8209;response](/plugins/jspsych-canvas-slider-response) | Draw a stimulus on a [HTML canvas element](https://www.w3schools.com/html/html5_canvas.asp), and ask the subject to respond by moving a slider to indicate a value. Useful for displaying dynamic, parametrically-defined graphics, and for controlling the positioning of multiple graphical elements (shapes, text, images).
[jspsych&#8209;categorize&#8209;animation](/plugins/jspsych-categorize-animation) | The subject responds to an animation and can be given feedback about their response.
[jspsych&#8209;categorize&#8209;html](/plugins/jspsych-categorize-html) | The subject responds to an HTML-formatted stimulus using the keyboard and can be given feedback about the correctness of their response.
[jspsych&#8209;categorize&#8209;image](/plugins/jspsych-categorize-image) | The subject responds to an image using the keyboard and can be given feedback about the correctness of their response.
[jspsych&#8209;cloze](/plugins/jspsych-cloze) | Plugin for displaying a cloze test and checking participants answers against a correct solution.
[jspsych&#8209;external&#8209;html](/plugins/jspsych-external-html) | Displays an external HTML page (such as a consent form) and lets the subject respond by clicking a button or pressing a key. Plugin can validate their response, which is useful for making sure that a subject has granted consent before starting the experiment.
[jspsych&#8209;free&#8209;sort](/plugins/jspsych-free-sort) | Displays a set of images on the screen in random locations. Subjects can click and drag the images to move them around the screen. Records all the moves made by the subject, so the sequence of moves can be recovered from the data.
[jspsych&#8209;fullscreen](/plugins/jspsych-fullscreen) | Toggles the experiment in and out of fullscreen mode.
[jspsych&#8209;html&#8209;button&#8209;response](/plugins/jspsych-html-button-response) | Display an HTML-formatted stimulus and allow the subject to respond by choosing a button to click. The button can be customized extensively, e.g., using images in place of standard buttons.
[jspsych&#8209;html&#8209;keyboard&#8209;response](/plugins/jspsych-html-keyboard-response) | Display an HTML-formatted stimulus and allow the subject to respond by pressing a key.
[jspsych&#8209;html&#8209;slider&#8209;response](/plugins/jspsych-html-slider-response) | Display an HTML-formatted stimulus and allow the subject to respond by moving a slider to indicate a value.
[jspsych&#8209;iat&#8209;html](/plugins/jspsych-iat-html) | The implicit association task, using HTML-formatted stimuli.
[jspsych&#8209;iat&#8209;image](/plugins/jspsych-iat-image) | The implicit association task, using images as stimuli.
[jspsych&#8209;image&#8209;button&#8209;response](/plugins/jspsych-image-button-response) | Display an image and allow the subject to respond by choosing a button to click. The button can be customized extensively, e.g., using images in place of standard buttons.
[jspsych&#8209;image&#8209;keyboard&#8209;response](/plugins/jspsych-image-keyboard-response) | Display an image and allow the subject to respond by pressing a key.
[jspsych&#8209;image&#8209;slider&#8209;response](/plugins/jspsych-image-slider-response) | Display an image and allow the subject to respond by moving a slider to indicate a value.
[jspsych&#8209;instructions](/plugins/jspsych-instructions) | For displaying instructions to the subject. Allows the subject to navigate between pages of instructions using keys or buttons.
[jspsych&#8209;maxdiff](/plugins/jspsych-maxdiff) | Displays rows of alternatives to be selected for two mutually-exclusive categories, typically as 'most' or 'least' on a particular criteria (e.g. importance, preference, similarity). The participant responds by selecting one radio button corresponding to an alternative in both the left and right response columns.
[jspsych&#8209;preload](/plugins/jspsych-preload) | This plugin loads images, audio, and video files into the browser's memory before they are needed in the experiment, in order to improve stimulus and response timing, and to avoid disrupting the flow of the experiment.
[jspsych&#8209;rdk](/plugins/jspsych-rdk) | This plugin displays a Random Dot Kinematogram (RDK) and allows the subject to report the primary direction of motion by pressing a key on the keyboard.
[jspsych&#8209;reconstruction](/plugins/jspsych-reconstruction) | The subject interacts with a stimulus by modifying a parameter of the stimulus and observing the change in the stimulus in real-time.
[jspsych&#8209;resize](/plugins/jspsych-resize) | Calibrate the display so that materials display with a known physical size.
[jspsych&#8209;same&#8209;different&#8209;html](/plugins/jspsych-same-different-html) | A same-different judgment task. An HTML-formatted stimulus is shown, followed by a brief gap, and then another stimulus is shown. The subject indicates whether the stimuli are the same or different.
[jspsych&#8209;same&#8209;different&#8209;image](/plugins/jspsych-same-different-image) | A same-different judgment task. An image is shown, followed by a brief gap, and then another stimulus is shown. The subject indicates whether the stimuli are the same or different.
[jspsych&#8209;serial&#8209;reaction&#8209;time](/plugins/jspsych-serial-reaction-time) | A set of boxes are displayed on the screen and one of them changes color. The subject presses a key that corresponds to the different color box as fast as possible.
[jspsych&#8209;serial&#8209;reaction&#8209;time&#8209;mouse](/plugins/jspsych-serial-reaction-time-mouse) | A set of boxes are displayed on the screen and one of them changes color. The subjects clicks the box that changed color as fast as possible.
[jspsych&#8209;survey&#8209;html&#8209;form](/plugins/jspsych-survey-html-form) | Renders a custom HTML form. Allows for mixing multiple kinds of form input.
[jspsych&#8209;survey&#8209;likert](/plugins/jspsych-survey-likert) | Displays likert-style questions.
[jspsych&#8209;survey&#8209;multi&#8209;choice](/plugins/jspsych-survey-multi-choice) | Displays multiple choice questions with one answer allowed per question.
[jspsych&#8209;survey&#8209;multi&#8209;select](/plugins/jspsych-survey-multi-select) | Displays multiple choice questions with multiple answes allowed per question.
[jspsych&#8209;survey&#8209;text](/plugins/jspsych-survey-text) | Shows a prompt with a text box. The subject writes a response and then submits by clicking a button.
[jspsych&#8209;video&#8209;button&#8209;response](/plugins/jspsych-video-button-response) | Displays a video file with many options for customizing playback. Subject responds to the video by pressing a button.
[jspsych&#8209;video&#8209;keyboard&#8209;response](/plugins/jspsych-video-keyboard-response) | Displays a video file with many options for customizing playback. Subject responds to the video by pressing a key.
[jspsych&#8209;video&#8209;slider&#8209;response](/plugins/jspsych-video-slider-response) | Displays a video file with many options for customizing playback. Subject responds to the video by moving a slider.
[jspsych&#8209;visual&#8209;search&#8209;circle](/plugins/jspsych-visual-search-circle) | A customizable visual-search task modelled after [Wang, Cavanagh, & Green (1994)](http://dx.doi.org/10.3758/BF03206946). The subject indicates whether or not a target is present among a set of distractors. The stimuli are displayed in a circle, evenly-spaced, equidistant from a fixation point.
[jspsych&#8209;vsl&#8209;animate&#8209;occlusion](/plugins/jspsych-vsl-animate-occlusion) | A visual statistical learning paradigm based on [Fiser & Aslin (2002)](http://dx.doi.org/10.1037//0278-7393.28.3.458). A sequence of stimuli are shown in an oscillatory motion. An occluding rectangle is in the center of the display, and the stimuli change when they are behind the rectangle.
[jspsych&#8209;vsl&#8209;grid&#8209;scene](/plugins/jspsych-vsl-grid-scene) | A visual statistical learning paradigm based on [Fiser & Aslin (2001)](http://dx.doi.org/10.1111/1467-9280.00392). A scene made up of individual stimuli arranged in a grid is shown. This plugin can also generate the HTML code to render the stimuli for use in other plugins.
[jspsych&#8209;webgazer&#8209;calibrate](/plugins/jspsych-webgazer-calibrate) | Calibrates the WebGazer extension for eye tracking.
[jspsych&#8209;webgazer&#8209;init&#8209;camera](/plugins/jspsych-webgazer-init-camera) | Initializes the camera and helps the participant center their face for eye tracking.
[jspsych&#8209;webgazer&#8209;validate](/plugins/jspsych-webgazer-validate) | Performs validation to measure precision and accuracy of WebGazer eye tracking predictions.

View File

@ -1,107 +0,0 @@
# Plugins
In jsPsych, plugins define the kinds of tasks that subjects perform in experiments. Some plugins define very general tasks, like displaying instructions or displaying a visual stimulus and getting a keyboard response. Other plugins are more specific, displaying particular kinds of interactive stimuli, or running a specific version of particular kind of task. Creating an experiment with jsPsych involves figuring out which plugins are needed for the kinds of tasks you want to have your subjects perform.
Plugins provide a structure for a particular task, but often allow for significant customization and flexibility. For example, the `jspsych-image-keyboard-response` plugin defines a simple structure for showing an image and collecting a keyboard response. You can specify the what the stimulus is, what keys the subject is allowed to press, and how long the stimulus should be on the screen, how long the subject has to respond, and so on. Many of these content options have reasonable default values; even though the `jspsych-image-keyboard-response` plugin has many different options, you only *need* to specify the stimulus in order to use it. Each plugin has its own documentation page, which describes what the plugin does and what options are available.
## Using a plugin
To use a plugin, you'll need to load the plugin's JavaScript file on your experiment page:
```html
<head>
<script src="jspsych/plugins/jspsych-image-keyboard-response.js" type="text/javascript"></script>
</head>
```
Once a plugin is loaded, you can define a trial that uses that plugin. The following JavaScript code defines a trial using the `jspsych-image-keyboard-response` plugin to display an image file ('images/happy_face.jpg'). This trial uses the default values for valid keys, length of display, and other parameters. You could override these values by adding them to the object.
```javascript
var single_stim_trial = {
type: 'image-keyboard-response',
stimulus: 'images/happy_face.jpg'
}
```
Here's an exampe of overriding the default value for `post_trial_gap`:
```javascript
var single_stim_trial = {
type: 'image-keyboard-response',
stimulus: 'images/happy_face.jpg',
post_trial_gap: 2000
}
```
## Parameters available in all plugins
Each plugin specifies its own set of parameters. Check the documentation for a plugin to see what parameters are available and what they do.
In addition, there is a set of parameters that can be specified for any plugin.
Parameter | Type | Default Value | Description
----------|------|---------------|------------
post_trial_gap | numeric | null | Sets the time, in milliseconds, between the current trial and the next trial. If null, there will be no gap.
on_finish | function | `function(){ return; }` | A callback function to execute when the trial finishes. See [this page](../overview/callbacks.md) for more details.
on_start | function | `function(){ return; }` | A callback function to execute when the trial begins, before any loading has occurred. See [this page](../overview/callbacks.md) for more details.
on_load | function | `function(){ return; }` | A callback function to execute when the trial has loaded, which typically happens after the initial display of the plugin has loaded. See [this page](../overview/callbacks.md) for more details.
data | object | *undefined* | An object containing additional data to store for the trial. See [this page](../overview/data.md) for more details.
## Data collected by plugins
Each plugin defines what data is collected on the trial. The documentation for each plugin specifies what data is collected by that plugin.
In addition to the data collected by a plugin, there is a default set of data that is collected on every trial. The collected data are:
Name | Type | Value
-----|------|------
trial_type | string | The name of the plugin used to run the trial.
trial_index | numeric | The index of the current trial across the whole experiment.
time_elapsed | numeric | The number of milliseconds since the start of the experiment when the trial ended.
internal_node_id | string | A string identifier for the current TimelineNode.
## List of available plugins
This table is a description of all plugins that are distributed with jsPsych. Click on the name of a plugin to view its documentation page.
Plugin | Description
------ | -----------
[jspsych&#8209;animation](jspsych-animation) | Shows a sequence of images at a specified frame rate. Records key presses (including timing information) made by the subject while they are viewing the animation.
[jspsych&#8209;audio&#8209;button&#8209;response](jspsych-audio-button-response) | Play an audio file and allow the subject to respond by choosing a button to click. The button can be customized extensively, e.g., using images in place of standard buttons.
[jspsych&#8209;audio&#8209;keyboard&#8209;response](jspsych-audio-keyboard-response) | Play an audio file and allow the subject to respond by pressing a key.
[jspsych&#8209;audio&#8209;slider&#8209;response](jspsych-audio-slider-response) | Play an audio file and allow the subject to respond by moving a slider to indicate a value.
[jspsych&#8209;call&#8209;function](jspsych-call-function) | Executes an arbitrary function call. Doesn't display anything to the subject, and the subject is usually unaware that this plugin has even executed. It's useful for performing tasks at specified times in the experiment, such as saving data.
[jspsych&#8209;categorize&#8209;animation](jspsych-categorize-animation) | The subject responds to an animation and can be given feedback about their response.
[jspsych&#8209;categorize&#8209;html](jspsych-categorize-html) | The subject responds to an HTML-formatted stimulus using the keyboard and can be given feedback about the correctness of their response.
[jspsych&#8209;categorize&#8209;image](jspsych-categorize-image) | The subject responds to an image using the keyboard and can be given feedback about the correctness of their response.
[jspsych&#8209;cloze](jspsych-cloze) | Plugin for displaying a cloze test and checking participants answers against a correct solution.
[jspsych&#8209;external&#8209;html](jspsych-external-html) | Displays an external HTML page (such as a consent form) and lets the subject respond by clicking a button or pressing a key. Plugin can validate their response, which is useful for making sure that a subject has granted consent before starting the experiment.
[jspsych&#8209;free&#8209;sort](jspsych-free-sort) | Displays a set of images on the screen in random locations. Subjects can click and drag the images to move them around the screen. Records all the moves made by the subject, so the sequence of moves can be recovered from the data.
[jspsych&#8209;fullscreen](jspsych-fullscreen) | Toggles the experiment in and out of fullscreen mode.
[jspsych&#8209;html&#8209;button&#8209;response](jspsych-html-button-response) | Display an HTML-formatted stimulus and allow the subject to respond by choosing a button to click. The button can be customized extensively, e.g., using images in place of standard buttons.
[jspsych&#8209;html&#8209;keyboard&#8209;response](jspsych-html-keyboard-response) | Display an HTML-formatted stimulus and allow the subject to respond by pressing a key.
[jspsych&#8209;html&#8209;slider&#8209;response](jspsych-html-slider-response) | Display an HTML-formatted stimulus and allow the subject to respond by moving a slider to indicate a value.
[jspsych&#8209;iat&#8209;html](jspsych-iat-html) | The implicit association task, using HTML-formatted stimuli.
[jspsych&#8209;iat&#8209;image](jspsych-iat-image) | The implicit association task, using images as stimuli.
[jspsych&#8209;image&#8209;button&#8209;response](jspsych-image-button-response) | Display an image and allow the subject to respond by choosing a button to click. The button can be customized extensively, e.g., using images in place of standard buttons.
[jspsych&#8209;image&#8209;keyboard&#8209;response](jspsych-image-keyboard-response) | Display an image and allow the subject to respond by pressing a key.
[jspsych&#8209;image&#8209;slider&#8209;response](jspsych-image-slider-response) | Display an image and allow the subject to respond by moving a slider to indicate a value.
[jspsych&#8209;instructions](jspsych-instructions) | For displaying instructions to the subject. Allows the subject to navigate between pages of instructions using keys or buttons.
[jspsych&#8209;rdk](jspsych-rdk) | This plugin displays a Random Dot Kinematogram (RDK) and allows the subject to report the primary direction of motion by pressing a key on the keyboard.
[jspsych&#8209;reconstruction](jspsych-reconstruction) | The subject interacts with a stimulus by modifying a parameter of the stimulus and observing the change in the stimulus in real-time.
[jspsych&#8209;resize](jspsych-resize) | Calibrate the display so that materials display with a known physical size.
[jspsych&#8209;same&#8209;different&#8209;html](jspsych-same-different-html) | A same-different judgment task. An HTML-formatted stimulus is shown, followed by a brief gap, and then another stimulus is shown. The subject indicates whether the stimuli are the same or different.
[jspsych&#8209;same&#8209;different&#8209;image](jspsych-same-different-image) | A same-different judgment task. An image is shown, followed by a brief gap, and then another stimulus is shown. The subject indicates whether the stimuli are the same or different.
[jspsych&#8209;serial&#8209;reaction&#8209;time](jspsych-serial-reaction-time) | A set of boxes are displayed on the screen and one of them changes color. The subject presses a key that corresponds to the different color box as fast as possible.
[jspsych&#8209;serial&#8209;reaction&#8209;time&#8209;mouse](jspsych-serial-reaction-time-mouse) | A set of boxes are displayed on the screen and one of them changes color. The subjects clicks the box that changed color as fast as possible.
[jspsych&#8209;survey&#8209;html&#8209;form](jspsych-survey-html-form) | Renders a custom HTML form. Allows for mixing multiple kinds of form input.
[jspsych&#8209;survey&#8209;likert](jspsych-survey-likert) | Displays likert-style questions.
[jspsych&#8209;survey&#8209;multi&#8209;choice](jspsych-survey-multi-choice) | Displays multiple choice questions with one answer allowed per question.
[jspsych&#8209;survey&#8209;multi&#8209;select](jspsych-survey-multi-select) | Displays multiple choice questions with multiple answes allowed per question.
[jspsych&#8209;survey&#8209;text](jspsych-survey-text) | Shows a prompt with a text box. The subject writes a response and then submits by clicking a button.
[jspsych&#8209;video&#8209;button&#8209;response](jspsych-video-button-response) | Displays a video file with many options for customizing playback. Subject responds to the video by pressing a button.
[jspsych&#8209;video&#8209;keyboard&#8209;response](jspsych-video-keyboard-response) | Displays a video file with many options for customizing playback. Subject responds to the video by pressing a key.
[jspsych&#8209;video&#8209;slider&#8209;response](jspsych-video-slider-response) | Displays a video file with many options for customizing playback. Subject responds to the video by moving a slider.
[jspsych&#8209;visual&#8209;search&#8209;circle](jspsych-visual-search-circle) | A customizable visual-search task modelled after [Wang, Cavanagh, & Green (1994)](http://dx.doi.org/10.3758/BF03206946). The subject indicates whether or not a target is present among a set of distractors. The stimuli are displayed in a circle, evenly-spaced, equidistant from a fixation point.
[jspsych&#8209;vsl&#8209;animate&#8209;occlusion](jspsych-vsl-animate-occlusion) | A visual statistical learning paradigm based on [Fiser & Aslin (2002)](http://dx.doi.org/10.1037//0278-7393.28.3.458). A sequence of stimuli are shown in an oscillatory motion. An occluding rectangle is in the center of the display, and the stimuli change when they are behind the rectangle.
[jspsych&#8209;vsl&#8209;grid&#8209;scene](jspsych-vsl-grid-scene) | A visual statistical learning paradigm based on [Fiser & Aslin (2001)](http://dx.doi.org/10.1111/1467-9280.00392). A scene made up of individual stimuli arranged in a grid is shown. This plugin can also generate the HTML code to render the stimuli for use in other plugins.

View File

@ -4,28 +4,46 @@ In the long tradition of **"Hello world!"** examples, this tutorial creates an e
## Step 1: Download the jsPsych library
Start by downloading the jsPsych library. The most recent version can always be found on the [GitHub releases page](https://github.com/jodeleeuw/jsPsych/releases).
Start by downloading the jsPsych library. The most recent version can always be found on the [GitHub releases page](https://github.com/jspsych/jsPsych/releases).
*Note: the image below shows version 4.2, but the process is the same for the most recent version.*
![releasespage](/img/githubreleases.jpg)
!!! warning
We strongly recommend downloading the latest release of the code rather than downloading the zip file of the code via the *Big Green Button* on the GitHub site. Downloading the code via the *Big Green Button* may give you a copy of the library that is in development and contains bugs.
## Step 2: Create a folder to store your experiment files
Create a folder on your computer to put the experiment files in. Once you've created the folder, open the downloaded archive from step 1, and move the extracted folder (called `jspsych-6.0.5` if using v6.0.5 of jsPsych) into the experiment folder. Here's what it looks like on a Windows machine:
Create a folder on your computer to put the experiment files in. Once you've created the folder, open the downloaded archive from step 1, and move the extracted folder (called `jspsych-6.3.0` if using v6.3.0 of jsPsych) into the experiment folder.
![folder setup](/img/folder-setup.png)
```
📂 My Experiment
-- 📂 jspsych-6.3.0
```
If you open up the `jspsych-6.3.0` folder you should see this structure.
```
📂 My Experiment
-- 📂 jspsych-6.3.0
---- 📂 css
---- 📂 examples
---- 📂 plugins
---- 📄 jspsych.js
```
## Step 3: Create a new HTML file
To edit jsPsych code you'll need a programming-friendly text editor. Some free options are:
* [Atom](https://atom.io) (Windows, OSX, Linux)
* [VSCode](https://code.visualstudio.com/) (Windows, OSX, Linux)
To edit jsPsych code you'll need a programming-friendly text editor. A great free option is [Visual Studio Code](https://code.visualstudio.com/) (Windows, OSX, Linux).
Once you've got a text editor that you like, create a new file in the experiment folder called `experiment.html`
![folder setup](/img/folder-with-html.png)
```
📂 My Experiment
-- 📂 jspsych-6.3.0
-- 📄 experiment.html
```
## Step 4: Add the bare-minimum HTML code
@ -52,7 +70,7 @@ To use jsPsych, add a `<script>` tag to import the library.
<html>
<head>
<title>My experiment</title>
<script src="jspsych-6.0.5/jspsych.js"></script>
<script src="jspsych-6.3.0/jspsych.js"></script>
</head>
<body></body>
</html>
@ -65,8 +83,8 @@ You may also want to import the jsPsych stylesheet, which applies a basic set of
<html>
<head>
<title>My experiment</title>
<script src="jspsych-6.0.5/jspsych.js"></script>
<link href="jspsych-6.0.5/css/jspsych.css" rel="stylesheet" type="text/css"></link>
<script src="jspsych-6.3.0/jspsych.js"></script>
<link href="jspsych-6.3.0/css/jspsych.css" rel="stylesheet" type="text/css">
</head>
<body></body>
</html>
@ -81,9 +99,9 @@ For the demo, we want to show some text on the screen. This is exactly what the
<html>
<head>
<title>My experiment</title>
<script src="jspsych-6.0.5/jspsych.js"></script>
<script src="jspsych-6.0.5/plugins/jspsych-html-keyboard-response.js"></script>
<link href="jspsych-6.0.5/css/jspsych.css" rel="stylesheet" type="text/css"></link>
<script src="jspsych-6.3.0/jspsych.js"></script>
<script src="jspsych-6.3.0/plugins/jspsych-html-keyboard-response.js"></script>
<link href="jspsych-6.3.0/css/jspsych.css" rel="stylesheet" type="text/css">
</head>
<body></body>
</html>
@ -98,9 +116,9 @@ To add JavaScript code directly to the webpage we need to add a set of `<script>
<html>
<head>
<title>My experiment</title>
<script src="jspsych-6.0.5/jspsych.js"></script>
<script src="jspsych-6.0.5/plugins/jspsych-html-keyboard-response.js"></script>
<link href="jspsych-6.0.5/css/jspsych.css" rel="stylesheet" type="text/css"></link>
<script src="jspsych-6.3.0/jspsych.js"></script>
<script src="jspsych-6.3.0/plugins/jspsych-html-keyboard-response.js"></script>
<link href="jspsych-6.3.0/css/jspsych.css" rel="stylesheet" type="text/css">
</head>
<body></body>
<script>
@ -121,9 +139,9 @@ Now that we have the trial defined we just need to tell jsPsych to run an experi
<html>
<head>
<title>My experiment</title>
<script src="jspsych-6.0.5/jspsych.js"></script>
<script src="jspsych-6.0.5/plugins/jspsych-html-keyboard-response.js"></script>
<link href="jspsych-6.0.5/css/jspsych.css" rel="stylesheet" type="text/css"></link>
<script src="jspsych-6.3.0/jspsych.js"></script>
<script src="jspsych-6.3.0/plugins/jspsych-html-keyboard-response.js"></script>
<link href="jspsych-6.3.0/css/jspsych.css" rel="stylesheet" type="text/css">
</head>
<body></body>
<script>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,5 @@
# Video tutorials
A variety of video tutorials are available on [Josh de Leeuw's YouTube channel](https://www.youtube.com/playlist?list=PLnfo1lBY1P2Mf_o6rV5wiqqn92Mw3UTGh). Some tutorials walk through creating a basic version of an entire experiment, like the tutorial on creating a [dichotic listening experiment](https://www.youtube.com/playlist?list=PLnfo1lBY1P2Mf_o6rV5wiqqn92Mw3UTGh) aimed at new users. Others focus on specific features of jsPsych, like how to use [functions as parameters](https://www.youtube.com/watch?v=8-j2aAZ_iOk&list=PLnfo1lBY1P2Mf_o6rV5wiqqn92Mw3UTGh&index=5) to create experiments that change in response to participant input or how to [create a new plugin](https://www.youtube.com/watch?v=XQcsFwAmbiw&list=PLnfo1lBY1P2Mf_o6rV5wiqqn92Mw3UTGh&index=4).
Recordings from a Summer 2020 workshop on conducting online research with jsPsych are available on the [workshop's YouTube channel](https://www.youtube.com/channel/UCBZ5F1UysHWlplUNDRwbsWA). [Session 1](https://www.youtube.com/watch?v=BuhfsIFRFe8) provides an overview of jsPsych suitable for brand new users. [Session 3](https://www.youtube.com/watch?v=LP7o0iAALik) covers some more advanced features of jsPsych.

View File

@ -4,7 +4,7 @@
<script src="../jspsych.js"></script>
<script src="../plugins/jspsych-html-keyboard-response.js"></script>
<script src="../plugins/jspsych-image-keyboard-response.js"></script>
<link rel="stylesheet" href="../css/jspsych.css"></link>
<link rel="stylesheet" href="../css/jspsych.css">
</head>
<body></body>
<script>
@ -17,7 +17,8 @@
jsPsych.addNodeToEndOfTimeline({
timeline: [{
type: 'image-keyboard-response',
stimulus: 'img/happy_face_4.jpg'
stimulus: 'img/happy_face_4.jpg',
stimulus_width: 300
}]
}, jsPsych.resumeExperiment)
}

View File

@ -0,0 +1,46 @@
<!DOCTYPE html>
<html>
<head>
<script src="../jspsych.js"></script>
<script src="../plugins/jspsych-html-keyboard-response.js"></script>
<script src="../plugins/jspsych-html-button-response.js"></script>
<link rel="stylesheet" href="../css/jspsych.css">
</head>
<body></body>
<script>
var trial_1 = {
type: 'html-keyboard-response',
stimulus: '<p>By default, jsPsych does not treat letter responses as case sensitive. So "A" (uppercase) is treated as "a" (lowercase).</p>'+
'<p>This is an example of an experiment where "case_sensitive_responses" is set to "true" in jsPsych.init.</p>'+
'<p>To continue, you must press the letter "a" (lowercase).</p>'+
'<p>The trial will not end if you respond with "A" (uppercase), either by holding down the Shift key or turning CapsLock on.</p>',
choices: ['a']
}
var trial_2 = {
type: 'html-keyboard-response',
stimulus: '<p>This is another example trial.</p>'+
'<p>To continue, now you must press the letter "A" (uppercase).</p>'+
'<p>The trial will not end if you respond with "a" (lowercase).</p>',
choices: ['A']
}
var trial_3 = {
type: 'html-keyboard-response',
choices: jsPsych.ALL_KEYS,
stimulus: '<p>When "case_sensitive_responses" is "true", your keyboard responses are case-sensitive in the data.</p>'+
'<p>The next page shows the data, with your response recorded as "a" for the first trial and "A" for the second trial.</p>'+
'<p>If you change "case_sensitive_responses" to "false" in jsPsych.init and reload this expeirment<br>'+
'you will find that both "a" or "A" responses are valid responses for the first two trials,<br>'+
'and your response will always be recorded as "a" (lowercase) in the data.</p>'
}
jsPsych.init({
timeline: [trial_1, trial_2, trial_3],
case_sensitive_responses: true, // to ignore the letter case of a keyboard response, set this parameter to false or remove it
on_finish: function(){jsPsych.data.displayData(); }
});
</script>
</html>

View File

@ -3,21 +3,21 @@
<head>
<script src="../jspsych.js"></script>
<script src="../plugins/jspsych-html-keyboard-response.js"></script>
<link rel="stylesheet" href="../css/jspsych.css"></link>
<link rel="stylesheet" href="../css/jspsych.css">
</head>
<body></body>
<script>
var trial = {
type: 'html-keyboard-response',
stimulus: 'Hello. This is in a loop. Press R to repeat this trial, or C to continue.',
stimulus: 'Hello. This is in a loop. Press "r" to repeat this trial, or "c" to continue.',
choices: ['r','c']
}
var loop_node = {
timeline: [trial],
loop_function: function(data){
if(jsPsych.pluginAPI.convertKeyCharacterToKeyCode('r') == data.values()[0].key_press){
if(data.values()[0].response == 'r'){
return true;
} else {
return false;
@ -27,7 +27,7 @@
var pre_if_trial = {
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.',
choices: ['s','v']
}
@ -40,7 +40,7 @@
timeline: [if_trial],
conditional_function: function(){
var data = jsPsych.data.get().last(1).values()[0];
if(data.key_press == jsPsych.pluginAPI.convertKeyCharacterToKeyCode('s')){
if(data.response == 's'){
return false;
} else {
return true;

View File

@ -0,0 +1,139 @@
<!DOCTYPE html>
<html>
<head>
<script src="../jspsych.js"></script>
<script src="../plugins/jspsych-image-keyboard-response.js"></script>
<script src="../plugins/jspsych-html-keyboard-response.js"></script>
<link rel="stylesheet" href="../css/jspsych.css">
<style>
/*
Any CSS classes listed in the 'css_classes' parameter will only be added to the jspsych-content div.
Certain CSS rules will automatically be applied to all other elements _inside_ this div (stimulus, prompt, etc.),
through CSS inheritance. However, not all CSS properties are inherited from parent elements.
To learn more about CSS inheritance, see:
https://developer.mozilla.org/en-US/docs/Web/CSS/inheritance
https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Cascade_and_inheritance#inheritance
https://stackoverflow.com/questions/5612302/which-css-properties-are-inherited
In the CSS rules below, the rules are applied to the jspsych-content div, and then applied to
other elements inside of the jspsych-content div through inheritance. This is why both the stimulus and
prompt are affected by these rules in the trial_procedure_1 trials.
*/
.condition1 {
color: red;
font: small-caps bold 25px/25px Arial, sans-serif;
line-height: 150%;
}
.condition2 {
font-size: 20px;
font-weight: bold;
text-shadow: 2px 2px white;
line-height: 200%;
background-color: lightgray
}
/*
It's also possible to use more specific CSS selectors so that the CSS rule only affects certain elements on the page.
To create these CSS rules, we start with the class name used in "css_classes". This will select the 'parent' element (jspsych-content div):
.left-align
After that, add the more specific CSS selector(s) to select any particular element(s) that should be modified inside the parent element.
For example, to select only the "p" elements that are inside of the 'parent' element, you can use this:
.left-align p {...}
This method allows you to use different styles for different 'child' elements inside the jspsych-content div.
This method also allows you to modify properties that can't be modified through inheritance.
Options for CSS selectors include the element's tag name, ID, class, and combinations of these.
For example, to select a the element with the ID "jspsych-html-keyboard-response-stimulus":
.left-align #jspsych-html-keyboard-response-stimulus {...}
Or to select all "p" elements that also have the class "stimulus":
.left-align p.stimulus {...}
See here for more info about CSS selectors: https://www.w3schools.com/css/css_selectors.asp
In the trial_procedure_2 trials, the stimulus text is inside of <p> tags and the prompt text is not inside of <p> tags.
Therefore the CSS rules below will only affect the stimulus element in these trials.
*/
.left-align p {text-align: left; width: 600px;}
.right-align p {text-align: right; width: 600px;}
.teal p {color: teal;}
.purple p {color: purple;}
.large-text p {font-size: 40px; line-height: 1.5em;}
.black-border p {border: 4px solid black;}
/*
The CSS rules below are used in trial_procedure_3 to format the fixation cross
and move the img element to the left or right.
*/
.fixation {font-size: 90px; font-weight: bold;}
.img-left img {transform: translate(-300px);}
.img-right img {transform: translate(300px);}
</style>
</head>
<body></body>
<script>
var trial_procedure_1 = {
timeline: [{
type: 'html-keyboard-response',
stimulus: jsPsych.timelineVariable('stim'),
css_classes: jsPsych.timelineVariable('css_class'),
prompt: 'This is the prompt.<br>In this set of trials, the CSS styles are applied to the parent element<br>'+
'and passed on to all other jsPsych content through inheritance,<br>'+
'which is why they also affect both the stimulus and prompt text.<br>Press any key to continue.'
}],
timeline_variables: [
{css_class: ['condition1'], stim: '<p>This is a Condition 1 stimulus.</p>'},
{css_class: ['condition2'], stim: '<p>This is a Condition 2 stimulus.</p>'}
]
}
var trial_procedure_2 = {
timeline: [{
type: 'html-keyboard-response',
stimulus: '<p>This is the stimulus.</p>',
css_classes: jsPsych.timelineVariable('css_classes'),
prompt: 'In this set of trials, the CSS rules are applied more selectively<br>so that they only affect the stimulus text, not the prompt text<br>'+
'(see the comments in the HTML file for more information).<br>Press any key to continue.'
}],
timeline_variables: [
{css_classes: ['teal','left-align','black-border','large-text']},
{css_classes: ['teal','right-align','black-border','large-text']},
{css_classes: ['purple','left-align','large-text']},
{css_classes: ['purple','right-align','large-text']}
]
}
var trial_procedure_3 = {
timeline: [
{
type: 'html-keyboard-response',
stimulus: '+',
choices: jsPsych.NO_KEYS,
trial_duration: 500,
css_classes: ['fixation']
},
{
type: 'image-keyboard-response',
stimulus: 'img/blue.png',
css_classes: jsPsych.timelineVariable('image_side'),
prompt: '<p>Press <strong>f</strong> if the image is on the <strong>left</strong>.</p>'+
'<p>Press <strong>j</strong> if the image is on the <strong>right</strong>.</p>',
choices: ['f','j'],
render_on_canvas: false
}
],
timeline_variables: [
{image_side: ['img-left'], correct_response: 'f'},
{image_side: ['img-right'], correct_response: 'j'}
]
}
jsPsych.init({
timeline: [trial_procedure_1, trial_procedure_2, trial_procedure_3],
on_finish: function() {
jsPsych.data.displayData();
}
});
</script>
</html>

View File

@ -4,20 +4,17 @@
<head>
<script src="../jspsych.js"></script>
<script src="../plugins/jspsych-image-keyboard-response.js"></script>
<link rel="stylesheet" href="../css/jspsych.css"></link>
<style>
img {
width: 300px;
}
</style>
<link rel="stylesheet" href="../css/jspsych.css">
</head>
<body></body>
<script>
var block_1 = {
type: 'image-keyboard-response',
stimulus: 'img/happy_face_1.jpg',
choices: [89, 78], // Y or N
prompt: '<p>The data displayed on the next page should have a subject and completed property. Press Y or N.</p>'
choices: ['y','n'],
render_on_canvas: false,
stimulus_width: 300,
prompt: '<p>The data displayed on the next page should have a subject and completed property. Press "y" or "n".</p>'
}
jsPsych.data.addProperties({

View File

@ -4,20 +4,16 @@
<head>
<script src="../jspsych.js"></script>
<script src="../plugins/jspsych-image-keyboard-response.js"></script>
<link rel="stylesheet" href="../css/jspsych.css"></link>
<style>
img {
width: 300px;
}
</style>
<link rel="stylesheet" href="../css/jspsych.css">
</head>
<body></body>
<script>
var block_1 = {
type: 'image-keyboard-response',
stimulus: 'img/happy_face_1.jpg',
choices: [89, 78], // Y or N
prompt: '<p>Data should have a random int 0-19 on next page. Y or N.</p>',
choices: ['y','n'],
prompt: '<p>Data should have a random int 0-19 on next page. Press "y" or "n".</p>',
stimulus_width: 300,
data: function() {
return {
random_number: Math.floor(Math.random() * 20)

View File

@ -1,16 +1,9 @@
<!DOCTYPE html>
<html>
<head>
<script src="../jspsych.js"></script>
<script src="../plugins/jspsych-image-keyboard-response.js"></script>
<link rel="stylesheet" href="../css/jspsych.css"></link>
<style>
img {
width: 300px;
}
</style>
<link rel="stylesheet" href="../css/jspsych.css">
</head>
<body></body>
<script>
@ -29,8 +22,9 @@
var node = {
type: 'image-keyboard-response',
timeline: [trial_1, trial_2, trial_3],
choices: [89, 78], // Y or N
prompt: '<p>Have you seen this face before? Y or N.</p>',
choices: ['y','n'],
prompt: '<p>Have you seen this face before? Press "y" or "n".</p>',
stimulus_width: 300,
data: {
node_data: true
},
@ -39,7 +33,6 @@
}
}
jsPsych.init({
timeline: [node],
on_finish: function() {

View File

@ -2,7 +2,7 @@
<html>
<head>
<script src="../jspsych.js"></script>
<link rel="stylesheet" href="../css/jspsych.css"></link>
<link rel="stylesheet" href="../css/jspsych.css">
</head>
<body>
<p>The URL variable should be logged to the console</p>

View File

@ -5,6 +5,7 @@
<script src="../jspsych.js"></script>
<script src="../plugins/jspsych-html-keyboard-response.js"></script>
<script src="../plugins/jspsych-image-keyboard-response.js"></script>
<script src="../plugins/jspsych-preload.js"></script>
<link rel="stylesheet" href="../css/jspsych.css">
</head>
<body>
@ -54,15 +55,15 @@
var test = {
timeline: [{
type: 'image-keyboard-response',
choices: [37, 39],
choices: ['ArrowLeft', 'ArrowRight'],
trial_duration: 1500,
stimulus: jsPsych.timelineVariable('stimulus'),
data: jsPsych.timelineVariable('data'),
on_finish: function(data){
var correct = false;
if(data.direction == 'left' && data.key_press == 37 && data.rt > -1){
if(data.direction == 'left' && data.response == 'ArrowLeft' && data.rt > -1){
correct = true;
} else if(data.direction == 'right' && data.key_press == 39 && data.rt > -1){
} else if(data.direction == 'right' && data.response == 'ArrowRight' && data.rt > -1){
correct = true;
}
data.correct = correct;
@ -90,8 +91,16 @@
}
};
// manually preload images due to presenting them with timeline variables
var images = ["img/con1.png","img/con2.png","img/inc1.png","img/inc2.png"];
var preload = {
type: 'preload',
images: images
}
/*set up experiment structure*/
var timeline = [];
timeline.push(preload);
timeline.push(welcome);
timeline.push(instructions);
timeline.push(test);

View File

@ -1,104 +1,120 @@
<!DOCTYPE html>
<html>
<head>
<title>My experiment</title>
<script src="../jspsych.js"></script>
<script src="../plugins/jspsych-html-keyboard-response.js"></script>
<script src="../plugins/jspsych-image-keyboard-response.js"></script>
<link rel="stylesheet" href="../css/jspsych.css"></link>
</head>
<body></body>
<script>
/* create timeline */
var timeline = [];
<head>
<title>My experiment</title>
<script src="../jspsych.js"></script>
<script src="../plugins/jspsych-html-keyboard-response.js"></script>
<script src="../plugins/jspsych-image-keyboard-response.js"></script>
<script src="../plugins/jspsych-preload.js"></script>
<link rel="stylesheet" href="../css/jspsych.css">
</head>
/* define welcome message trial */
var welcome_block = {
type: "html-keyboard-response",
stimulus: "Welcome to the experiment. Press any key to begin."
};
timeline.push(welcome_block);
<body></body>
<script>
/* create timeline */
var timeline = [];
/* define instructions trial */
var instructions = {
type: "html-keyboard-response",
stimulus: "<p>In this experiment, a circle will appear in the center " +
"of the screen.</p><p>If the circle is <strong>blue</strong>, " +
"press the letter F on the keyboard as fast as you can.</p>" +
"<p>If the circle is <strong>orange</strong>, press the letter J " +
"as fast as you can.</p>" +
"<div style='width: 700px;'>"+
"<div style='float: left;'><img src='img/blue.png'></img>" +
"<p class='small'><strong>Press the F key</strong></p></div>" +
"<div class='float: right;'><img src='img/orange.png'></img>" +
"<p class='small'><strong>Press the J key</strong></p></div>" +
"</div>"+
"<p>Press any key to begin.</p>",
post_trial_gap: 2000
};
timeline.push(instructions);
/* preload images */
var preload = {
type: 'preload',
images: ['img/blue.png', 'img/orange.png']
}
timeline.push(preload);
/* test trials */
/* define welcome message trial */
var welcome = {
type: "html-keyboard-response",
stimulus: "Welcome to the experiment. Press any key to begin."
};
timeline.push(welcome);
var test_stimuli = [
{ stimulus: "img/blue.png", data: { test_part: 'test', correct_response: 'f' } },
{ stimulus: "img/orange.png", data: { test_part: 'test', correct_response: 'j' } }
];
/* define instructions trial */
var instructions = {
type: "html-keyboard-response",
stimulus: `
<p>In this experiment, a circle will appear in the center
of the screen.</p><p>If the circle is <strong>blue</strong>,
press the letter F on the keyboard as fast as you can.</p>
<p>If the circle is <strong>orange</strong>, press the letter J
as fast as you can.</p>
<div style='width: 700px;'>
<div style='float: left;'><img src='img/blue.png'></img>
<p class='small'><strong>Press the F key</strong></p></div>
<div class='float: right;'><img src='img/orange.png'></img>
<p class='small'><strong>Press the J key</strong></p></div>
</div>
<p>Press any key to begin.</p>
`,
post_trial_gap: 2000
};
timeline.push(instructions);
var fixation = {
type: 'html-keyboard-response',
stimulus: '<div style="font-size:60px;">+</div>',
choices: jsPsych.NO_KEYS,
trial_duration: function(){
return jsPsych.randomization.sampleWithoutReplacement([250, 500, 750, 1000, 1250, 1500, 1750, 2000], 1)[0];
},
data: {test_part: 'fixation'}
/* test trials */
var test_stimuli = [
{ stimulus: "img/blue.png", correct_response: 'f' },
{ stimulus: "img/orange.png", correct_response: 'j' }
];
var fixation = {
type: 'html-keyboard-response',
stimulus: '<div style="font-size:60px;">+</div>',
choices: jsPsych.NO_KEYS,
trial_duration: function () {
return jsPsych.randomization.sampleWithoutReplacement([250, 500, 750, 1000, 1250, 1500, 1750, 2000], 1)[0];
},
data: {
task: 'fixation'
}
}
var test = {
type: "image-keyboard-response",
stimulus: jsPsych.timelineVariable('stimulus'),
choices: ['f', 'j'],
data: jsPsych.timelineVariable('data'),
on_finish: function(data){
data.correct = data.key_press == jsPsych.pluginAPI.convertKeyCharacterToKeyCode(data.correct_response);
},
var test = {
type: "image-keyboard-response",
stimulus: jsPsych.timelineVariable('stimulus'),
choices: ['f', 'j'],
data: {
task: 'response',
correct_response: jsPsych.timelineVariable('correct_response')
},
on_finish: function (data) {
data.correct = data.response == data.correct_response;
}
}
var test_procedure = {
timeline: [fixation, test],
timeline_variables: test_stimuli,
repetitions: 5,
randomize_order: true
}
timeline.push(test_procedure);
/* define debrief */
var debrief_block = {
type: "html-keyboard-response",
stimulus: function () {
var trials = jsPsych.data.get().filter({ task: 'response' });
var correct_trials = trials.filter({ correct: true });
var accuracy = Math.round(correct_trials.count() / trials.count() * 100);
var rt = Math.round(correct_trials.select('rt').mean());
return `<p>You responded correctly on ${accuracy}% of the trials.</p>
<p>Your average response time was ${rt}ms.</p>
<p>Press any key to complete the experiment. Thank you!</p>`;
var test_procedure = {
timeline: [fixation, test],
timeline_variables: test_stimuli,
repetitions: 5,
randomize_order: true
}
timeline.push(test_procedure);
};
timeline.push(debrief_block);
/* define debrief */
/* start the experiment */
jsPsych.init({
timeline: timeline,
on_finish: function () {
jsPsych.data.displayData();
}
});
</script>
var debrief_block = {
type: "html-keyboard-response",
stimulus: function() {
var trials = jsPsych.data.get().filter({test_part: 'test'});
var correct_trials = trials.filter({correct: true});
var accuracy = Math.round(correct_trials.count() / trials.count() * 100);
var rt = Math.round(correct_trials.select('rt').mean());
return "<p>You responded correctly on "+accuracy+"% of the trials.</p>"+
"<p>Your average response time was "+rt+"ms.</p>"+
"<p>Press any key to complete the experiment. Thank you!</p>";
}
};
timeline.push(debrief_block);
/* start the experiment */
jsPsych.init({
timeline: timeline,
on_finish: function() {
jsPsych.data.displayData();
}
});
</script>
</html>
</html>

View File

@ -3,12 +3,7 @@
<head>
<script src="../../jspsych.js"></script>
<script src="../../plugins/jspsych-image-keyboard-response.js"></script>
<link rel="stylesheet" href="../../css/jspsych.css"></link>
<style>
img {
width: 300px;
}
</style>
<link rel="stylesheet" href="../../css/jspsych.css">
</head>
<body>
</body>
@ -16,22 +11,28 @@
var trial_1 = {
type: "image-keyboard-response",
stimulus: '../img/happy_face_1.jpg',
choices: [89, 78],
prompt: '<p>Is this face happy? Y or N.</p>'
choices: ['y','n'],
render_on_canvas: false,
stimulus_width: 300,
prompt: '<p>Is this face happy? Press "y" or "n".</p>'
}
var trial_2 = {
type: 'image-keyboard-response',
stimulus: '../img/sad_face_2.jpg',
choices: [89, 78], // Y or N
prompt: '<p>Is this face happy? Y or N.</p>'
choices: ['y','n'],
render_on_canvas: false,
stimulus_width: 300,
prompt: '<p>Is this face happy? Press "y" or "n".</p>'
}
var trial_3 = {
type: 'image-keyboard-response',
stimulus: '../img/happy_face_2.jpg',
choices: [89, 78], // Y or N
prompt: '<p>Is this face happy? Y or N.</p>',
choices: ['y','n'],
render_on_canvas: false,
stimulus_width: 300,
prompt: '<p>Is this face happy? Press "y" or "n".</p>',
}
@ -40,4 +41,4 @@
default_iti: 250
});
</script>
</html>
</html>

View File

@ -23,7 +23,7 @@
var test = {
timeline: [{
type: 'html-keyboard-response',
choices: [37, 39],
choices: ["ArrowLeft", "ArrowRight"],
stimulus: jsPsych.timelineVariable('stimulus'),
data: jsPsych.timelineVariable('data'),
post_trial_gap: 1500,

View File

@ -6,12 +6,9 @@
<script src="../jspsych.js"></script>
<script src="../plugins/jspsych-image-keyboard-response.js"></script>
<script src="../plugins/jspsych-html-keyboard-response.js"></script>
<link rel="stylesheet" href="../css/jspsych.css"></link>
<link rel="stylesheet" href="../css/jspsych.css">
<style>
p { line-height: 1.5em; font-size: 18px; }
img {
width: 300px;
}
#jspsych-experiment { width: 600px; height: 400px; float: right; overflow: hidden; margin: 25px; border: 1px solid #999;}
</style>
</head>
@ -34,33 +31,34 @@
var trial_1 = {
type: 'image-keyboard-response',
stimulus: 'img/happy_face_1.jpg',
choices: [89, 78], // Y or N
prompt: '<p>Have you seen this face before? Y or N.</p>'
choices: ['y','n'],
prompt: '<p>Have you seen this face before? Press "y" or "n".</p>',
stimulus_width: 300,
render_on_canvas: false
}
var trial_2 = {
type: 'image-keyboard-response',
stimulus: 'img/happy_face_2.jpg',
choices: [89, 78], // Y or N
timing_response: 5000,
prompt: '<p>Have you seen this face before? Y or N. (5s time limit).</p>'
choices: ['y','n'],
trial_duration: 5000,
prompt: '<p>Have you seen this face before? Press "y" or "n". (5s time limit).</p>',
stimulus_width: 300,
render_on_canvas: false
}
var trial_3 = {
type: 'html-keyboard-response',
choices: jsPsych.NO_KEYS, // Y or N
timing_response: 5000,
choices: jsPsych.NO_KEYS,
trial_duration: 5000,
prompt: '<p>No response allowed. 5s wait.</p>',
stimulus: '<p>:)</p>',
is_html: true
stimulus: '<p>:)</p>'
}
var node = {
type: 'html-keyboard-response',
timeline: [trial_1, trial_2, trial_3],
}
jsPsych.init({
timeline: [node],
display_element: 'jspsych-experiment',

View File

@ -1,17 +1,10 @@
<!DOCTYPE html>
<html>
<head>
<script src="../jspsych.js"></script>
<script src="../plugins/jspsych-html-keyboard-response.js"></script>
<script src="../plugins/jspsych-image-keyboard-response.js"></script>
<link rel="stylesheet" href="../css/jspsych.css"></link>
<style>
img {
width: 300px;
}
</style>
<link rel="stylesheet" href="../css/jspsych.css">
</head>
<body></body>
<script>
@ -26,10 +19,12 @@
var block = {
type: 'image-keyboard-response',
choices: [89, 78], // Y or N
prompt: '<p>Press Y to Continue. Press N to end this node of the experiment.</p>',
choices: ['y','n'],
stimulus_width: 300,
render_on_canvas: false,
prompt: '<p>Press "y" to continue. Press "n" to end this node of the experiment.</p>',
on_finish: function(data) {
if (data.key_press == 78) {
if (data.response == "n") {
jsPsych.endCurrentTimeline();
}
},
@ -38,7 +33,7 @@
var after_block = {
type: 'html-keyboard-response',
stimulus: '<p>The next node</p>',
stimulus: '<p>The next node.</p>',
}
jsPsych.init({

View File

@ -4,7 +4,7 @@
<head>
<script src="../jspsych.js"></script>
<script src="../plugins/jspsych-image-keyboard-response.js"></script>
<link rel="stylesheet" href="../css/jspsych.css"></link>
<link rel="stylesheet" href="../css/jspsych.css">
<style>
img {
width: 300px;
@ -24,10 +24,11 @@
var block = {
type: 'image-keyboard-response',
choices: [89, 78], // Y or N
prompt: '<p>Press Y to Continue. Press N to end the experiment</p>',
choices: ['y','n'],
prompt: '<p>Press "y" to continue. Press "n" to end the experiment.</p>',
render_on_canvas: false,
on_finish: function(data) {
if (data.key_press == 78) {
if (data.response == 'n') {
jsPsych.endExperiment('The experiment was ended. This is the end message.');
}
},

Some files were not shown because too many files have changed in this diff Show More