Merge branch 'master' into feature-eye-tracking-improvements

This commit is contained in:
Josh de Leeuw 2021-04-09 12:16:23 -04:00 committed by GitHub
commit cec803c7fa
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 223 additions and 208 deletions

View File

@ -2,7 +2,8 @@
---
## jsPsych.addNodeToEndOfTimeline
```
```javascript
jsPsych.addNodeToEndOfTimeline(node_parameters)
```
@ -20,9 +21,7 @@ None.
Adds the timeline to the end of the experiment.
### Examples
#### Without callback
### Example
```javascript
var trial = {
@ -37,28 +36,10 @@ var new_timeline = {
jsPsych.addNodeToEndOfTimeline(new_timeline)
```
### With callback
```javascript
var first = {
type: 'html-keyboard-response',
stimulus: 'first trial; new trial added when on_finish is called',
on_finish: function(){
jsPsych.pauseExperiment();
jsPsych.addNodeToEndOfTimeline({
timeline: [{
type: 'image-keyboard-response',
stimulus: 'img/happy_face_4.jpg'
}]
}, jsPsych.resumeExperiment)
}
}
```
---
## jsPsych.allTimelineVariables
```
```javascript
jsPsych.allTimelineVariables()
```
@ -91,7 +72,7 @@ var trial = {
---
## jsPsych.currentTimelineNodeID
```
```javascript
jsPsych.currentTimelineNodeID()
```
@ -131,14 +112,13 @@ The rules about iterations apply throughout the hierarchical ID:
```javascript
var id = jsPsych.currentTimelineNodeID();
console.log('The current TimelineNode ID is '+id);
```
---
## jsPsych.currentTrial
```
```javascript
jsPsych.currentTrial()
```
@ -157,16 +137,15 @@ Get a description of the current trial
### Example
```javascript
var trial = jsPsych.currentTrial();
console.log('The current trial is using the '+trial.type+' plugin');
```
---
## jsPsych.endCurrentTimeline
```
jsPsych.endCurrentTimeline
```javascript
jsPsych.endCurrentTimeline()
```
### Parameters
@ -186,7 +165,6 @@ Ends the current timeline. If timelines are nested, then only the timeline that
#### End timeline if a particular key is pressed
```javascript
var images = [
"img/1.gif", "img/2.gif", "img/3.gif", "img/4.gif",
"img/5.gif", "img/6.gif", "img/7.gif", "img/8.gif",
@ -223,13 +201,12 @@ jsPsych.init({
jsPsych.data.displayData();
}
});
```
---
## jsPsych.endExperiment
```
```javascript
jsPsych.endExperiment(end_message)
```
@ -268,7 +245,7 @@ var trial = {
---
## jsPsych.finishTrial
```
```javascript
jsPsych.finishTrial(data)
```
@ -297,15 +274,14 @@ This method tells jsPsych that the current trial is over. It is used in all of t
### Example
```javascript
// this code would be in a plugin
jsPsych.finishTrial({correct_response: true});
```
---
## jsPsych.getDisplayElement
```
```javascript
jsPsych.getDisplayElement()
```
@ -333,7 +309,7 @@ el.style.visibility = 'hidden';
---
## jsPsych.getProgressBarCompleted
```
```javascript
jsPsych.getProgressBarCompleted()
```
@ -358,7 +334,7 @@ var progress_bar_amount = jsPsych.getProgressBarCompleted();
---
## jsPsych.init
```
```javascript
jsPsych.init(settings)
```
@ -413,9 +389,10 @@ This method configures and starts the experiment.
See any of the plugin examples in the [examples folder](https://github.com/jodeleeuw/jsPsych/tree/master/examples) in the GitHub repository.
---
## jsPsych.initSettings
```
```javascript
jsPsych.initSettings()
```
@ -441,8 +418,10 @@ console.log(JSON.stringify(settings.timeline));
```
---
## jsPsych.pauseExperiment
```
```javascript
jsPsych.pauseExperiment()
```
@ -475,9 +454,10 @@ var trial = {
```
---
## jsPsych.progress
```
```javascript
jsPsych.progress()
```
@ -503,15 +483,15 @@ This method returns information about the length of the experiment and the subje
### Example
```javascript
var progress = jsPsych.progress();
alert('You have completed approximately '+progress.percent_complete+'% of the experiment');
```
```
---
## jsPsych.resumeExperiment
```
```javascript
jsPsych.resumeExperiment()
```
@ -544,9 +524,10 @@ var trial = {
```
---
## jsPsych.setProgressBar
```
```javascript
jsPsych.setProgressBar(value)
```
@ -572,9 +553,10 @@ jsPsych.setProgressBar(0.85);
```
---
## jsPsych.startTime
```
```javascript
jsPsych.startTime()
```
@ -597,21 +579,20 @@ var start_time = jsPsych.startTime();
```
---
## jsPsych.timelineVariable
```
```javascript
jsPsych.timelineVariable(variable, call_immediate)
```
### Parameters
Parameter | Type | Description
----------|------|------------
variable | string | Name of the timeline variable
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
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.
@ -623,6 +604,7 @@ Either a function that returns the value of the timeline variable, or the value
### Examples
#### Standard use as a parameter for a trial
```javascript
var trial = {
type: 'image-keyboard-response',
@ -641,6 +623,7 @@ var procedure = {
```
#### Invoking immediately in a function
```javascript
var trial = {
type: 'html-keyboard-response',
@ -659,7 +642,9 @@ var procedure = {
]
}
```
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',
@ -680,9 +665,10 @@ var procedure = {
```
---
## jsPsych.totalTime
```
```javascript
jsPsych.totalTime()
```
@ -701,17 +687,16 @@ Gets the total time the subject has been in the experiment.
### Example
```javascript
var time = jsPsych.totalTime();
console.log(time);
```
---
## jsPsych.version
```
jsPsych.version
```javascript
jsPsych.version()
```
### Parameters

View File

@ -3,9 +3,10 @@
The jsPsych.data module contains functions for interacting with the data generated by jsPsych plugins.
---
## jsPsych.data.addProperties
```
```javascript
jsPsych.data.addProperties(properties)
```
@ -23,19 +24,19 @@ Returns nothing.
This method appends a set of properties to every trial in the data object, including trials that have already occurred and trials that have yet to occur. You can use this to record things like the subject ID or condition assignment.
### Examples
#### Assigning a subject ID and condition code
```javascript
jsPsych.data.addProperties({subject: 1, condition: 'control'});
```
---
## jsPsych.data.displayData
```
```javascript
jsPsych.data.displayData(format)
```
@ -56,6 +57,7 @@ Outputs all of the data collected in the experiment to the screen in either JSON
### Examples
#### Using the on_finish callback function to show data at the end of the experiment
```javascript
jsPsych.init({
experiment_structure: exp,
@ -66,6 +68,7 @@ jsPsych.init({
```
---
## jsPsych.data.get
```
@ -97,9 +100,10 @@ console.log(all_data.csv());
```
---
## jsPsych.data.getDataByTimelineNode
```
```javascript
jsPsych.data.getDataByTimelineNode(node_id)
```
@ -120,17 +124,15 @@ Get all the data generated by a specified Timeline.
### Example
```javascript
var current_node_id = jsPsych.currentTimelineNodeID();
var data_from_current_node = jsPsych.data.getDataByTimelineNode(current_node_id);
```
---
## jsPsych.data.getInteractionData
```
```javascript
jsPsych.data.getInteractionData()
```
@ -162,11 +164,11 @@ var interaction_data = jsPsych.data.getInteractionData();
console.log(interaction_data.json());
```
---
## jsPsych.data.getLastTimelineData
```
```javascript
jsPsych.data.getLastTimelineData()
```
@ -180,20 +182,21 @@ Gets all of the data generated in the same timeline as the last trial.
### Example
```js
```javascript
var lasttimelinedata = jsPsych.data.getLastTimelineData();
```
---
## jsPsych.data.getLastTrialData
```
```javascript
jsPsych.data.getLastTrialData()
```
### Return value
Returns a DataCollection
Returns a DataCollection.
### Description
@ -201,14 +204,15 @@ Gets the data collection containing all data generated by the last trial.
### Example
```
```javascript
var lasttrialdata = jsPsych.data.getLastTrialData();
```
---
## jsPsych.data.getURLVariable
```
```javascript
jsPsych.data.getURLVariable(var_name)
```
@ -226,21 +230,19 @@ Returns the value of a variable passed in through the query string.
For extracting a particular variable passed in through a URL query string.
### Examples
### Example
```javascript
// if the URL of the page is: experiment.html?subject=1234&condition=test
console.log(jsPsych.data.getURLVariable('subject')) // logs "1234"
console.log(jsPsych.data.getURLVariable('condition')) // logs "test"
```
---
## jsPsych.data.urlVariables
```
```javascript
jsPsych.data.urlVariables()
```
@ -252,23 +254,20 @@ Returns an object (associative array) of the variables in the URL query string.
For extracting variables passed in through a URL query string.
### Examples
### Example
```javascript
// if the URL of the page is: experiment.html?subject=1234&condition=test
var urlvar = jsPsych.data.urlVariables();
console.log(urlvar.subject) // logs "1234"
console.log(urlvar.condition) // logs "test"
```
---
## jsPsych.data.write
```
```javascript
jsPsych.data.write(data_object)
```
@ -286,10 +285,9 @@ Returns nothing.
This method is used by `jsPsych.finishTrial` for writing data. You should probably not use it to add data. Instead use [jsPsych.data.addProperties](#addProperties).
### Examples
### Example
```javascript
// don't use this! data should only be written once per trial. use jsPsych.finishTrial to save data.
var trial_data = {
@ -298,20 +296,19 @@ var trial_data = {
}
jsPsych.data.write(trial_data);
```
---
## DataCollection
All data is stored in the DataCollection object. Using methods like `jsPsych.data.get()` and `jsPsych.data.getLastTrialData()` return DataCollections containing
the experiment data. This is a list of all of the methods that are available to call on a DataCollection object.
All data is stored in the DataCollection object. Using methods like `jsPsych.data.get()` and `jsPsych.data.getLastTrialData()` return DataCollections containing the experiment data. This is a list of all of the methods that are available to call on a DataCollection object.
#### .addToAll()
Adds a set of properties to all items in the DataCollection. Similar to `jsPsych.data.addProperties()`, except that it can be applied to a subset of the whole DataCollection by filtering down to a smaller DataCollection first.
```js
```javascript
jsPsych.data.get().addToAll({subject_id: 123, condition: 'control'});
```
@ -319,7 +316,7 @@ jsPsych.data.get().addToAll({subject_id: 123, condition: 'control'});
Adds a set of properties to the last trial in the DataCollection.
```js
```javascript
jsPsych.data.get().addToLast({success: true});
```
@ -327,7 +324,7 @@ jsPsych.data.get().addToLast({success: true});
Counts the number of trials in the DataCollection.
```js
```javascript
jsPsych.data.get().count()
```
@ -335,7 +332,7 @@ jsPsych.data.get().count()
Generates a CSV string representing all of the data in the DataCollection.
```js
```javascript
console.log(jsPsych.data.get().csv());
```
@ -343,27 +340,27 @@ console.log(jsPsych.data.get().csv());
Returns a subset of the DataCollection based on the filter. The filter is an object, and trials are only kept in the returned DataCollection if they contain the key: value pair(s) in the filter object. For example, the code below selects all of the trials with a correct response.
```js
```javascript
var correct_trials = jsPsych.data.get().filter({correct: true});
```
The object can have multiple key: value pairs, and the trials must match all of them in order to be included in the returned collection.
```js
```javascript
// keep only correct trials from the practice phase
var correct_practice_trials = jsPsych.data.get().filter({correct:true, phase: 'practice'});
```
The filter can also be an array of objects. In this case each object in the array acts as an OR filter. As long as the trial has all the key: value pairs of one of the objects in the array, it will appear in the returned collection.
```js
```javascript
// select trials from block 1 and block 5.
var trials = jsPsych.data.get().filter([{block: 1}, {block:5}]);
```
The filter method returns a DataCollection object, so methods can be chained onto a single statement.
```js
```javascript
// count the number of correct trials in block 1
var block_1_correct = jsPsych.data.get().filter({block:1, correct:true}).count();
```
@ -372,7 +369,7 @@ var block_1_correct = jsPsych.data.get().filter({block:1, correct:true}).count()
This method is similar to the `.filter()` method, except that it accepts a function as the filter. The function is passed a single argument, containing the data for a trial. If the function returns `true` the trial is included in the returned DataCollection.
```js
```javascript
// count the number of trials with a response time greater than 2000ms.
var too_long = jsPsych.data.get().filterCustom(function(trial){
return trial.rt > 2000;
@ -383,7 +380,7 @@ var too_long = jsPsych.data.get().filterCustom(function(trial){
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
```javascript
var first_trial = jsPsych.data.get().first(1);
var last_trial_with_correct_response = jsPsych.data.get().filter({correct: true}).last(1);
var last_10_trials = jsPsych.data.get().last(10);
@ -393,7 +390,7 @@ var last_10_trials = jsPsych.data.get().last(10);
Returns a DataCollection with all instances of a particular key removed from the dataset.
```js
```javascript
// log a csv file that does not contain the internal_node_id values for each trial
console.log(jsPsych.data.get().ignore('internal_node_id').csv());
```
@ -402,7 +399,7 @@ console.log(jsPsych.data.get().ignore('internal_node_id').csv());
Appends one DataCollection onto another and returns the combined collection.
```js
```javascript
// get a DataCollection with all trials that are either correct or
// have a response time greater than 200ms.
var dc1 = jsPsych.data.get().filter({correct: true});
@ -414,7 +411,7 @@ var data = dc1.join(dc2);
Generates a JSON string representing all of the data in the DataCollection.
```js
```javascript
console.log(jsPsych.data.get().json());
```
@ -434,7 +431,7 @@ jsPsych.data.get().localSave('csv','mydata.csv');
Add a new entry to the DataCollection. This method is mostly used internally, and you shouldn't need to call it under normal circumstances.
```js
```javascript
var data = {correct: true, rt: 500}
jsPsych.data.get().push(data);
```
@ -443,7 +440,7 @@ jsPsych.data.get().push(data);
Creates a copy of the DataCollection so that any modification of the values in the DataCollection will not affect the original.
```js
```javascript
// this line edits the rt property of the first trial
jsPsych.data.get().first(1).values()[0].rt = 100;
@ -461,7 +458,7 @@ jsPsych.data.get().first(1).values()[0].rt
Returns a DataColumn object (see documentation below) of a single property from a DataCollection object.
```js
```javascript
var rt_data = jsPsych.data.get().select('rt');
rt_data.mean()
```
@ -470,7 +467,7 @@ rt_data.mean()
Generates an array of all the unique key names in the set of trials contained in the DataCollection. This is especially useful when setting up a relational database (e.g., MySQL) where the column names need to be specified in advance.
```js
```javascript
console.log(jsPsych.data.get().uniqueNames());
```
@ -478,7 +475,7 @@ console.log(jsPsych.data.get().uniqueNames());
Returns the raw data array associated with the DataCollection. This array is modifiable, so changes to the array and values of objects in the array will change the DataCollection.
```js
```javascript
var raw_data = jsPsych.data.get().values();
// was response in first trial correct?
@ -490,6 +487,7 @@ if(raw_data[0].correct){
```
---
## DataColumn
DataColumn objects represent all the values of a single property in a DataCollection. They are generated by using the `.select()` method on a DataCollection. Once a DataColumn is generated, the following methods can be used.
@ -498,7 +496,7 @@ DataColumn objects represent all the values of a single property in a DataCollec
Checks if all values in the DataColumn return `true` when passed to a function. The function takes a single argument, which represents one value from the DataColumn.
```js
```javascript
// check if all the response times in the practice phase were under 1000ms
jsPsych.data.get().filter({phase: 'practice'}).select('correct').all(function(x) { return x < 1000; });
```
@ -507,7 +505,7 @@ jsPsych.data.get().filter({phase: 'practice'}).select('correct').all(function(x)
Counts the number of values in the DataColumn.
```js
```javascript
// count how many response times there are
jsPsych.data.get().select('rt').count();
```
@ -516,7 +514,7 @@ jsPsych.data.get().select('rt').count();
Counts the number of occurrences of each unique value in the DataColumn. Returns this value as an object, where each key is a unique value and the value of each key is the number of occurrences of that key.
```js
```javascript
// get frequencies of correct and incorrect responses
jsPsych.data.get().select('correct').frequencies();
```
@ -525,7 +523,7 @@ jsPsych.data.get().select('correct').frequencies();
Returns the maximum or minimum value in a DataColumn.
```js
```javascript
jsPsych.data.get().select('rt').max();
jsPsych.data.get().select('rt').min();
```
@ -534,7 +532,7 @@ jsPsych.data.get().select('rt').min();
Returns the average of all the values in a DataColumn.
```js
```javascript
jsPsych.data.get().select('rt').mean();
```
@ -542,7 +540,7 @@ jsPsych.data.get().select('rt').mean();
Returns the median of all the values in a DataColumn.
```js
```javascript
jsPsych.data.get().select('rt').median();
```
@ -550,7 +548,7 @@ jsPsych.data.get().select('rt').median();
Returns the standard deviation of the values in a DataColumn.
```js
```javascript
jsPsych.data.get().select('rt').sd();
```
@ -558,7 +556,7 @@ jsPsych.data.get().select('rt').sd();
Filters the DataColumn to include only values that return `true` when passed through the specified function.
```js
```javascript
// below results will be less than 200.
jsPsych.data.get().select('rt').subset(function(x){ return x < 200; }).max();
```
@ -567,7 +565,7 @@ jsPsych.data.get().select('rt').subset(function(x){ return x < 200; }).max();
Returns the sum of the values in a DataColumn.
```js
```javascript
jsPsych.data.get().select('rt').sum();
```
@ -575,7 +573,7 @@ jsPsych.data.get().select('rt').sum();
The raw array of values in the DataColumn.
```js
```javascript
// note that this is not a function call.
jsPsych.data.get().select('rt').values;
```
@ -584,6 +582,6 @@ jsPsych.data.get().select('rt').values;
Returns the variance of the values in a DataColumn.
```js
```javascript
jsPsych.data.get().select('rt').variance();
```

View File

@ -3,9 +3,10 @@
The pluginAPI module contains functions that are useful when developing new plugins.
---
## jsPsych.pluginAPI.cancelAllKeyboardResponses
```
```javascript
jsPsych.pluginAPI.cancelAllKeyboardResponses()
```
@ -21,16 +22,17 @@ Returns nothing.
Cancels all currently active keyboard listeners created by `jsPsych.pluginAPI.getKeyboardResponse`.
### Examples
### Example
```javascript
jsPsych.pluginAPI.cancelAllKeyboardResponses();
```
---
## jsPsych.pluginAPI.cancelKeyboardResponse
```
```javascript
jsPsych.pluginAPI.cancelKeyboardResponse(listener_id)
```
@ -48,8 +50,7 @@ Returns nothing.
Cancels a specific keyboard listener created by `jsPsych.pluginAPI.getKeyboardResponse`.
### Examples
### Example
```javascript
// create a persistent keyboard listener
@ -66,9 +67,10 @@ jsPsych.pluginAPI.cancelKeyboardResponse(listener_id);
```
---
## jsPsych.pluginAPI.clearAllTimeouts
```
```javascript
jsPsych.pluginAPI.clearAllTimeouts()
```
@ -82,12 +84,13 @@ Returns nothing.
### Description
Clears any pending timeouts that were set using jsPsych.pluginAPI.setTimeout()
Clears any pending timeouts that were set using jsPsych.pluginAPI.setTimeout().
---
## jsPsych.pluginAPI.compareKeys
```
```javascript
jsPsych.pluginAPI.compareKeys(key1, key2)
```
@ -113,6 +116,7 @@ We recommend using this function to compare keys in all plugin and experiment co
### Examples
#### Basic examples
```javascript
jsPsych.pluginAPI.compareKeys('a', 'A');
// returns true when case_sensitive_responses is false in jsPsych.init
@ -129,6 +133,7 @@ jsPsych.pluginAPI.compareKeys('space', 31);
```
#### Comparing a key response and key parameter value in plugins
```javascript
// this is the callback_function passed to jsPsych.pluginAPI.getKeyboardResponse
var after_response = function(info) {
@ -139,6 +144,7 @@ var after_response = function(info) {
```
#### Scoring a key response in experiment code
```javascript
var trial = {
type: 'html-keyboard-response',
@ -158,9 +164,10 @@ var trial = {
```
---
## jsPsych.pluginAPI.getAudioBuffer
```
```javascript
jsPsych.pluginAPI.getAudioBuffer(filepath)
```
@ -183,6 +190,7 @@ It is strongly recommended that you preload audio files before calling this meth
### Examples
#### HTML 5 Audio
```javascript
jsPsych.pluginAPI.getAudioBuffer('my-sound.mp3')
.then(function(audio){
@ -194,6 +202,7 @@ jsPsych.pluginAPI.getAudioBuffer('my-sound.mp3')
```
#### WebAudio API
```javascript
var context = jsPsych.pluginAPI.audioContext();
@ -212,9 +221,10 @@ jsPsych.pluginAPI.getAudioBuffer('my-sound.mp3')
See the `audio-keyboard-response` plugin for an example in a fuller context.
---
## jsPsych.pluginAPI.getAutoPreloadList
```
```javascript
jsPsych.pluginAPI.getAutoPreloadList(timeline)
```
@ -258,9 +268,10 @@ jsPsych.pluginAPI.getAutoPreloadList(timeline);
```
---
## jsPsych.pluginAPI.getKeyboardResponse
```
```javascript
jsPsych.pluginAPI.getKeyboardResponse(parameters)
```
@ -295,6 +306,7 @@ This function uses the `.key` value of the keyboard event, which is _case sensit
### Examples
#### Get a single response from any key
```javascript
var after_response = function(info){
@ -310,6 +322,7 @@ jsPsych.pluginAPI.getKeyboardResponse({
```
#### Get a responses from a key until the letter q is pressed
```javascript
var after_response = function(info){
@ -329,9 +342,10 @@ var listener = jsPsych.pluginAPI.getKeyboardResponse({
```
---
## jsPsych.pluginAPI.preloadAudio
```
```javascript
jsPsych.pluginAPI.preloadAudio(files, callback_complete, callback_load, callback_error)
```
@ -359,8 +373,8 @@ The `callback_load` and `callback_error` functions are called after each file ha
### Examples
#### Basic use
```javascript
```javascript
var sounds = ['file1.mp3', 'file2.mp3', 'file3.mp3'];
jsPsych.pluginAPI.preloadAudio(sounds,
@ -374,7 +388,6 @@ function startExperiment(){
timeline: exp
});
}
```
#### Show progress of loading
@ -386,7 +399,7 @@ var n_loaded = 0;
jsPsych.pluginAPI.preloadAudio(sounds, function(){ startExperiment(); }, function(file) { updateLoadedCount(file); });
function updateLoadedCount(file){
n_loaded++;
n_loaded++;
var percentcomplete = n_loaded / sounds.length * 100;
// could put something fancier here, like a progress bar
@ -395,16 +408,17 @@ function updateLoadedCount(file){
}
function startExperiment(){
jsPsych.init({
timeline: exp
});
jsPsych.init({
timeline: exp
});
}
```
---
## jsPsych.pluginAPI.preloadImages
```
```javascript
jsPsych.pluginAPI.preloadImages(images, callback_complete, callback_load, callback_error)
```
@ -432,8 +446,8 @@ The `callback_load` and `callback_error` functions are called after each file ha
### Examples
#### Basic use
```javascript
```javascript
var images = ['img/file1.png', 'img/file2.png', 'img/file3.png'];
jsPsych.pluginAPI.preloadImages(images,
@ -447,7 +461,6 @@ function startExperiment(){
timeline: exp
});
}
```
#### Show progress of loading
@ -459,7 +472,7 @@ var n_loaded = 0;
jsPsych.pluginAPI.preloadImages(images, function(){ startExperiment(); }, function(file) { updateLoadedCount(file); });
function updateLoadedCount(file){
n_loaded++;
n_loaded++;
var percentcomplete = n_loaded / images.length * 100;
// could put something fancier here, like a progress bar
@ -468,16 +481,17 @@ function updateLoadedCount(file){
}
function startExperiment(){
jsPsych.init({
timeline: exp
});
jsPsych.init({
timeline: exp
});
}
```
---
## jsPsych.pluginAPI.preloadVideo
```
```javascript
jsPsych.pluginAPI.preloadVideo(video, callback_complete, callback_load, callback_error)
```
@ -505,22 +519,21 @@ The `callback_load` and `callback_error` functions are called after each file ha
### Examples
#### Basic use
```javascript
```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(); },
function(file){ console.log('file loaded: ', file); }
function(file){ console.log('error loading file: ', file); }
);
function startExperiment(){
jsPsych.init({
timeline: exp
});
jsPsych.init({
timeline: exp
});
}
```
#### Show progress of loading
@ -532,7 +545,7 @@ var n_loaded = 0;
jsPsych.pluginAPI.preloadVideo(videos, function(){ startExperiment(); }, function(file) { updateLoadedCount(file); });
function updateLoadedCount(file){
n_loaded++;
n_loaded++;
var percentcomplete = n_loaded / videos.length * 100;
// could put something fancier here, like a progress bar
@ -541,16 +554,17 @@ function updateLoadedCount(file){
}
function startExperiment(){
jsPsych.init({
timeline: exp
});
jsPsych.init({
timeline: exp
});
}
```
---
## jsPsych.pluginAPI.registerPreload
```
```javascript
jsPsych.pluginAPI.registerPreload(plugin_name, parameter, media_type)
```
@ -578,7 +592,7 @@ For an example, see the [image-keyboard-response](https://github.com/jspsych/jsP
## jsPsych.pluginAPI.setTimeout
```
```javascript
jsPsych.pluginAPI.setTimeout(callback, delay)
```
@ -597,7 +611,7 @@ Returns the ID of the setTimeout handle.
This is simply a call to the standard setTimeout function in JavaScript with the added benefit of registering the setTimeout call in a central list. This is useful for scenarios where some other event (the trial ending, aborting the experiment) should stop the execution of queued timeouts.
### Examples
### Example
```javascript
// print the time

View File

@ -6,7 +6,7 @@ The jsPsych.randomization module contains methods that are useful for generating
## jsPsych.randomization.factorial
```
```javascript
jsPsych.randomization.factorial(factors, repetitions, unpack)
```
@ -29,6 +29,7 @@ This method takes a list of factors and their levels, and creates a full factori
### Examples
#### Create full factorial design
```javascript
var factors = {
stimulus: ['a.jpg', 'b.jpg'],
@ -49,6 +50,7 @@ full_design = [
```
#### Create full factorial design with repeats
```javascript
var factors = {
stimulus: ['a.jpg', 'b.jpg'],
@ -73,6 +75,7 @@ full_design = [
```
#### Create full factorial design, unpacked
```javascript
var factors = {
stimulus: ['a.jpg', 'b.jpg'],
@ -91,9 +94,10 @@ full_design = {
```
---
## jsPsych.randomization.randomID
```
```javascript
jsPsych.randomization.randomID(length)
```
@ -114,19 +118,18 @@ Generates a random string that is likely to be unique. If length is undefined, t
### Example
```javascript
console.log(jsPsych.randomization.randomID());
// outputs: "t7dwz0e713pc8juuaayyfvpkdd9un239"
console.log(jsPsych.randomization.randomID(8));
// outputs: "3xtpcbck"
```
---
## jsPsych.randomization.repeat
```
```javascript
jsPsych.randomization.repeat(array, repetitions, unpack)
```
@ -153,27 +156,22 @@ If the array elements are objects with the same set of properties, then this met
#### Shuffle an array, no repeats
```javascript
var myArray = [1,2,3,4,5];
var shuffledArray = jsPsych.randomization.repeat(myArray, 1);
// output: shuffledArray = [3,2,4,1,5]
```
#### Shuffle an array with repeats
```javascript
var myArray = [1,2,3,4,5];
var shuffledArray = jsPsych.randomization.repeat(myArray, 2);
// output: shuffledArray = [1,3,4,2,2,4,5,1,5,3]
```
#### Shuffle an array of objects
```javascript
var trial1 = {
stimulus: 'img/faceA.jpg',
correct_key: 'p',
@ -201,7 +199,6 @@ var shuffledArray = jsPsych.randomization.repeat(myArray, 2);
#### Shuffle an array of objects, with unpack
```javascript
var trial1 = {
stimulus: 'img/faceA.jpg',
correct_key: 'p',
@ -231,10 +228,12 @@ output: shuffledArray = {
}
*/
```
---
## jsPsych.randomization.sampleWithReplacement
```
```javascript
jsPsych.randomization.sampleWithReplacement(array, sampleSize, weights)
```
@ -259,27 +258,24 @@ This method returns a sample drawn at random from a set of values with replaceme
#### Sample with equal probability
```javascript
var myArray = [1,2,3,4,5];
var sample = jsPsych.randomization.sampleWithReplacement(myArray, 10);
// output: sample = [3, 1, 2, 2, 5, 1, 4, 3, 1, 5];
```
#### Sample with unequal probability
```javascript
var myArray = [1,2,3,4,5];
var sample = jsPsych.randomization.sampleWithReplacement(myArray, 10, [6,1,1,1,1]);
// output: sample = [3, 4, 5, 1, 2, 1, 3, 1, 1, 1];
```
---
## jsPsych.randomization.sampleWithoutReplacement
```
```javascript
jsPsych.randomization.sampleWithoutReplacement(array, sampleSize)
```
@ -303,17 +299,16 @@ This method returns a sample drawn at random from a set of values without replac
#### Sample without replacement
```javascript
var myArray = [1,2,3,4,5];
var sample = jsPsych.randomization.sampleWithoutReplacement(myArray, 2);
// output: sample = [3,2];
```
---
## jsPsych.randomization.shuffle
```
```javascript
jsPsych.randomization.shuffle(array)
```
@ -336,17 +331,16 @@ A simple method for shuffling the order of an array.
#### Shuffle an array
```javascript
var myArray = [1,2,3,4,5];
var shuffledArray = jsPsych.randomization.shuffle(myArray);
// output: shuffledArray = [3,2,4,1,5]
```
---
## jsPsych.randomization.shuffleNoRepeats
```
```javascript
jsPsych.randomization.shuffleNoRepeats(array, equalityTest)
```
@ -372,10 +366,8 @@ Shuffle an array, ensuring that neighboring elements in the array are different.
#### Basic example
```javascript
var myArray = [1,2,3,4,5,1,2,3,4,5,1,2,3,4,5];
var shuffledArray = jsPsych.randomization.shuffleNoRepeats(myArray);
// output: shuffledArray = [2, 3, 5, 1, 2, 4, 1, 5, 4, 1, 3, 5, 4, 3, 2]
```

View File

@ -3,9 +3,10 @@
The jsPsych.turk module contains functions for interacting with Mechanical Turk.
---
## jsPsych.turk.submitToTurk
```
```javascript
jsPsych.turk.submitToTurk(data)
```
@ -28,7 +29,6 @@ This method will only work when called from within the mechanical turk website.
### Example
```html
<p>Enter the code you were given:</p>
<input type="text" id="code"></input>
<button onclick="sendData();">Submit HIT</button>
@ -52,7 +52,7 @@ function sendData() {
## jsPsych.turk.turkInfo
```
```javascript
jsPsych.turk.turkInfo()
```
@ -78,7 +78,6 @@ This method returns basic information about the current Mechanical Turk session,
### Example
```javascript
var turkInfo = jsPsych.turk.turkInfo();
alert('Worker ID is: ' + turkInfo.workerId);
@ -97,6 +96,3 @@ alert('Preview mode? ' + turkInfo.previewMode);
// false otherwise.
alert('Outside turk? ' + turkInfo.outsideTurk);
```

View File

@ -36,7 +36,7 @@ var trial = {
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.
[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
@ -80,4 +80,4 @@ The four events that an extension must support are shown in the sample code.
`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.
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

@ -1,6 +1,6 @@
# 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).
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

View File

@ -8,7 +8,6 @@ jsPsych offers the ability to call arbitrary functions in response to certain ev
The `on_close` callback can be declared in the `jsPsych.init` method. The callback triggers when the user leaves the page, but before any content on the page is removed from the browser's memory. This can be used, for example, to save data as the user is leaving the page.
#### Sample use
```javascript
jsPsych.init({
timeline: exp,
@ -25,7 +24,6 @@ jsPsych.init({
The `on_data_update` callback can be declared in the `jsPsych.init` method. The callback triggers at the end of a data update cycle. This happens after every trial, after the on_finish (trial) and on_trial_finish events execute, allowing you to modify the data in those callbacks, and then use this callback to store the data. The function will be passed a single argument, which contains the data that was written.
#### Sample use
```javascript
jsPsych.init({
timeline: exp,
@ -34,13 +32,13 @@ jsPsych.init({
}
});
```
---
## on_finish (trial)
The `on_finish` callback can be added to any trial. The callback will trigger whenever the trial ends. The callback function will be passed a single argument, containing the data object from the trial. This data object is *editable*. Any changes made in the on_finish function will be stored in the internal data collection.
#### Sample use
```javascript
var trial = {
type: 'image-keyboard-response',
@ -54,13 +52,13 @@ var trial = {
}
};
```
---
## on_finish (experiment)
The `on_finish` callback can be declared in the `jsPsych.init` method. The callback will trigger once all trials in the experiment have been run. The method will be passed a single argument, containing all of the data generated in the experiment.
#### Sample use
```javascript
jsPsych.init({
timeline: exp,
@ -69,13 +67,13 @@ jsPsych.init({
}
});
```
---
## on_load
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',
@ -85,13 +83,13 @@ var trial = {
}
};
```
---
## on_start (trial)
The `on_start` callback can be added to any trial. The callback will trigger right before the trial begins. The callback function will be passed a single argument, containing the trial object. If any of the parameters of the trial are functions or timeline variables, these will be evaluated before `on_start` is called, and the trial object will contain the evaluated value. The trial object is modifiable, and any changes made will affect the trial.
#### Sample use
```javascript
var trial = {
type: 'image-keyboard-response',
@ -109,7 +107,6 @@ var trial = {
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],
@ -128,13 +125,13 @@ var procedure = {
}
}
```
---
## 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],
@ -147,13 +144,13 @@ var procedure = {
}
}
```
---
## 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.
#### Sample use
```javascript
jsPsych.init({
timeline: exp,
@ -163,14 +160,13 @@ jsPsych.init({
}
});
```
---
## on_trial_start
The `on_trial_start` callback can be declared in the `jsPsych.init` method. The callback will trigger at the start of every trial in the experiment. The function receives a single argument: a modifiable copy of the trial object that will be used to run the next trial. Changes can be made to this object to alter the parameters of the upcoming trial.
#### Sample use
```javascript
var current_score = 0; // a variable that is updated throughout the experiment to keep track of the current score.

View File

@ -23,6 +23,7 @@ Include the `webgazer.js` file in your experiment via a `<script>` tag.
The [webgazer extension](/extensions/jspsych-ext-webgazer.md) adds functionality to jsPsych for interacting with webgazer. Load it like you would a plugin file.
```html
<head>
<script src="jspsych/jspsych.js"></script>
@ -42,6 +43,7 @@ jsPsych.init({
})
```
!!! tip
Example experiments using WebGazer are available in the **/examples** folder of the jsPsych release. See `webgazer.html`, `webgazer_image.html`, and `webgazer_audio.html`.
@ -49,12 +51,14 @@ jsPsych.init({
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. This plugin will also trigger the experiment to request permission to access the user's webcam if it hasn't already been granted.
```js
var init_camera_trial = {
type: 'webgazer-init-camera'
}
```
### Calibration
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).
@ -69,10 +73,12 @@ var calibration_trial = {
}
```
### Validation
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',

View File

@ -22,7 +22,7 @@ trial_duration | numeric | null | How long to wait for the subject to make a res
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 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.
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. If the stimulus is an **animated gif**, you must set this parameter to false, because the canvas rendering method will only present static images.
## Data Generated

View File

@ -19,7 +19,7 @@ In addition to the [parameters available in all plugins](/overview/plugins#param
| 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. |
| 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. If the stimulus is an **animated gif**, you must set this parameter to false, because the canvas rendering method will only present static images. |
## Data Generated

View File

@ -26,7 +26,7 @@ prompt | string | null | This string can contain HTML markup. Any content here w
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.
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. If the stimulus is an **animated gif**, you must set this parameter to false, because the canvas rendering method will only present static images.
## Data Generated

View File

@ -2410,8 +2410,12 @@ jsPsych.pluginAPI = (function() {
} else {
return key1.toLowerCase() == key2.toLowerCase();
}
} else if (key1 === null && (typeof key2 === 'string' || Number.isFinite(key2)) || key2 === null && (typeof key1 === 'string' || Number.isFinite(key1))) {
return false;
} else if (key1 === null && key2 === null) {
return true;
} else {
console.error('Error in jsPsych.pluginAPI.compareKeys: arguments must be either numeric key codes or key strings.');
console.error('Error in jsPsych.pluginAPI.compareKeys: arguments must be numeric key codes, key strings, or null.');
return undefined;
}
}

View File

@ -297,6 +297,30 @@ describe('#compareKeys', function(){
expect(jsPsych.pluginAPI.compareKeys('q', 'Q')).toBe(true);
expect(jsPsych.pluginAPI.compareKeys('q', 'q')).toBe(true);
});
test('should accept null as argument, and return true if both arguments are null, and return false if one argument is null and other is string or numeric', function() {
const spy = jest.spyOn(console, 'error').mockImplementation();
expect(jsPsych.pluginAPI.compareKeys(null, 'Q')).toBe(false);
expect(jsPsych.pluginAPI.compareKeys(80, null)).toBe(false);
expect(jsPsych.pluginAPI.compareKeys(null, null)).toBe(true);
expect(console.error).not.toHaveBeenCalled();
spy.mockRestore();
});
test('should return undefined and produce a console warning if either/both arguments are not a string, integer, or null', function() {
const spy = jest.spyOn(console, 'error').mockImplementation();
var t1 = jsPsych.pluginAPI.compareKeys({}, 'Q');
var t2 = jsPsych.pluginAPI.compareKeys(true, null);
var t3 = jsPsych.pluginAPI.compareKeys(null, ['Q']);
expect(typeof t1).toBe('undefined');
expect(typeof t2).toBe('undefined');
expect(typeof t3).toBe('undefined');
expect(console.error).toHaveBeenCalledTimes(3);
expect(console.error.mock.calls).toEqual([
['Error in jsPsych.pluginAPI.compareKeys: arguments must be numeric key codes, key strings, or null.'],
['Error in jsPsych.pluginAPI.compareKeys: arguments must be numeric key codes, key strings, or null.'],
['Error in jsPsych.pluginAPI.compareKeys: arguments must be numeric key codes, key strings, or null.'],
]);
spy.mockRestore();
});
});
describe('#convertKeyCharacterToKeyCode', function(){