diff --git a/overview/experiment-options/index.html b/overview/experiment-options/index.html index 38afd471..7614b468 100755 --- a/overview/experiment-options/index.html +++ b/overview/experiment-options/index.html @@ -1610,13 +1610,13 @@

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.

+

There may be situations when you want key choices and responses to be case-sensitive. You can change this by setting the case_sensitive_responses parameter to true in jsPsych.init.

// 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
+    case_sensitive_responses: 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.

diff --git a/plugins/jspsych-webgazer-validate/index.html b/plugins/jspsych-webgazer-validate/index.html index af3a403e..fb08f3f5 100755 --- a/plugins/jspsych-webgazer-validate/index.html +++ b/plugins/jspsych-webgazer-validate/index.html @@ -65,7 +65,7 @@
- + Skip to content @@ -1450,7 +1450,7 @@ -

jspsych-webgazer-calibrate

+

jspsych-webgazer-validate

This plugin can be used to measure the accuracy and precision of gaze predictions made by the WebGazer extension. For a narrative description of eye tracking with jsPsych, see the eye tracking overview.

Parameters

In addition to the 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.

diff --git a/search/search_index.json b/search/search_index.json index 4f7bd7e9..78b8bcb6 100755 --- a/search/search_index.json +++ b/search/search_index.json @@ -1 +1 @@ -{"config":{"lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"\u00b6 jsPsych is a JavaScript library for running behavioral experiments in a web browser. The library provides a flexible framework for building a wide range of laboratory-like experiments that can be run online. To use jsPsych, you provide a description of the experiment in the form of a timeline . jsPsych handles things like determining which trial to run next, storing data, and randomization. jsPsych uses plugins to define what to do at each point on the timeline. Plugins are ready-made templates for simple experimental tasks like displaying instructions or displaying a stimulus and collecting a keyboard response. Plugins are very flexible to support a wide variety of experiments. It is easy to create your own plugin if you have experience with JavaScript programming. The page on timelines is a good place to start learning about jsPsych. From there, you might want to complete the Hello World! tutorial and the reaction time experiment tutorial .","title":"Introduction"},{"location":"#_1","text":"jsPsych is a JavaScript library for running behavioral experiments in a web browser. The library provides a flexible framework for building a wide range of laboratory-like experiments that can be run online. To use jsPsych, you provide a description of the experiment in the form of a timeline . jsPsych handles things like determining which trial to run next, storing data, and randomization. jsPsych uses plugins to define what to do at each point on the timeline. Plugins are ready-made templates for simple experimental tasks like displaying instructions or displaying a stimulus and collecting a keyboard response. Plugins are very flexible to support a wide variety of experiments. It is easy to create your own plugin if you have experience with JavaScript programming. The page on timelines is a good place to start learning about jsPsych. From there, you might want to complete the Hello World! tutorial and the reaction time experiment tutorial .","title":""},{"location":"about/about/","text":"About jsPsych \u00b6 jsPsych was created by Josh de Leeuw . There have been many other contributors to the library; thanks to all of them! Citation \u00b6 If you use jsPsych for academic work please cite the following paper. de Leeuw, J. R. (2015). jsPsych: A JavaScript library for creating behavioral experiments in a web browser. Behavior Research Methods , 47 (1), 1-12. doi:10.3758/s13428-014-0458-y. Response times \u00b6 Wondering if jsPsych can be used for research that depends on accurate response time measurement? For most purposes, the answer is yes. Response time measurements in jsPsych (and JavaScript in general) are comparable to those taken in standard lab software like Psychophysics Toolbox and E-Prime. Response times measured in JavaScript tend to be a little bit longer (10-40ms), but have similar variance. See the following references for extensive work on this topic. de Leeuw, J. R., & Motz, B. A. (2016). Psychophysics in a Web browser? Comparing response times collected with JavaScript and Psychophysics Toolbox in a visual search task. Behavior Research Methods , 48 (1), 1-12. Hilbig, B. E. (2016). Reaction time effects in lab- versus web-based research: Experimental evidence. Behavior Research Methods , 48 (4), 1718-1724. Pinet, S., Zielinski, C., Math\u00f4t, S. et al. (in press). Measuring sequences of keystrokes with jsPsych: Reliability of response times and interkeystroke intervals. Behavior Research Methods . Reimers, S., & Stewart, N. (2015). Presentation and response time accuracy in Adobe Flash and HTML5/JavaScript Web experiments. Behavior Research Methods , 47 (2), 309-327.","title":"About jsPsych"},{"location":"about/about/#about-jspsych","text":"jsPsych was created by Josh de Leeuw . There have been many other contributors to the library; thanks to all of them!","title":"About jsPsych"},{"location":"about/about/#citation","text":"If you use jsPsych for academic work please cite the following paper. de Leeuw, J. R. (2015). jsPsych: A JavaScript library for creating behavioral experiments in a web browser. Behavior Research Methods , 47 (1), 1-12. doi:10.3758/s13428-014-0458-y.","title":"Citation"},{"location":"about/about/#response-times","text":"Wondering if jsPsych can be used for research that depends on accurate response time measurement? For most purposes, the answer is yes. Response time measurements in jsPsych (and JavaScript in general) are comparable to those taken in standard lab software like Psychophysics Toolbox and E-Prime. Response times measured in JavaScript tend to be a little bit longer (10-40ms), but have similar variance. See the following references for extensive work on this topic. de Leeuw, J. R., & Motz, B. A. (2016). Psychophysics in a Web browser? Comparing response times collected with JavaScript and Psychophysics Toolbox in a visual search task. Behavior Research Methods , 48 (1), 1-12. Hilbig, B. E. (2016). Reaction time effects in lab- versus web-based research: Experimental evidence. Behavior Research Methods , 48 (4), 1718-1724. Pinet, S., Zielinski, C., Math\u00f4t, S. et al. (in press). Measuring sequences of keystrokes with jsPsych: Reliability of response times and interkeystroke intervals. Behavior Research Methods . Reimers, S., & Stewart, N. (2015). Presentation and response time accuracy in Adobe Flash and HTML5/JavaScript Web experiments. Behavior Research Methods , 47 (2), 309-327.","title":"Response times"},{"location":"about/contributing/","text":"Contributing to jsPsych \u00b6 Contributions to jsPsych are welcome! All of the code is managed through the GitHub repository. Steps for modifying the code \u00b6 Discuss the proposed change \u00b6 If you have a specific modification in mind -- for instance, a new feature or bug fix -- please open a new issue via GitHub . 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 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 . 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 \u00b6 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 \u00b6 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 \u00b6 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 \u00b6 Plugins are most useful when they are flexible. Avoid fixing the value of parameters that could be variables. This is especially important for any text that displays on the screen in order to facilitate use in multiple languages. Use the jsPsych.pluginAPI module when appropriate \u00b6 The pluginAPI module 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 \u00b6 When submitting a pull request to add your plugin, make sure to include a documentation page in the same style as the other docs pages. Documentation files exist in the docs directory. Include an example file \u00b6 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 \u00b6 Automated code testing for jsPsych is implemented with Jest . To run the tests, install Node and npm. Run npm install in the root jsPsych directory. Then run npm test . Plugins should have a testing file that validates the behavior of all the plugin parameters. See the /tests/plugins directory for examples.","title":"Contributing to jsPsych"},{"location":"about/contributing/#contributing-to-jspsych","text":"Contributions to jsPsych are welcome! All of the code is managed through the GitHub repository.","title":"Contributing to jsPsych"},{"location":"about/contributing/#steps-for-modifying-the-code","text":"","title":"Steps for modifying the code"},{"location":"about/contributing/#discuss-the-proposed-change","text":"If you have a specific modification in mind -- for instance, a new feature or bug fix -- please open a new issue via GitHub . 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 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 . Discussion posts can be useful for sharing code and getting feedback before requesting a change to the library.","title":"Discuss the proposed change"},{"location":"about/contributing/#fork-the-library-and-modify-the-code","text":"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.","title":"Fork the library and modify the code"},{"location":"about/contributing/#submit-a-pull-request","text":"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.","title":"Submit a pull request"},{"location":"about/contributing/#writing-new-plugins","text":"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.","title":"Writing new plugins"},{"location":"about/contributing/#make-the-plugin-as-general-as-possible","text":"Plugins are most useful when they are flexible. Avoid fixing the value of parameters that could be variables. This is especially important for any text that displays on the screen in order to facilitate use in multiple languages.","title":"Make the plugin as general as possible"},{"location":"about/contributing/#use-the-jspsychpluginapi-module-when-appropriate","text":"The pluginAPI module 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.","title":"Use the jsPsych.pluginAPI module when appropriate"},{"location":"about/contributing/#document-your-plugin","text":"When submitting a pull request to add your plugin, make sure to include a documentation page in the same style as the other docs pages. Documentation files exist in the docs directory.","title":"Document your plugin"},{"location":"about/contributing/#include-an-example-file","text":"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.","title":"Include an example file"},{"location":"about/contributing/#include-a-testing-file","text":"Automated code testing for jsPsych is implemented with Jest . To run the tests, install Node and npm. Run npm install in the root jsPsych directory. Then run npm test . Plugins should have a testing file that validates the behavior of all the plugin parameters. See the /tests/plugins directory for examples.","title":"Include a testing file"},{"location":"about/license/","text":"License \u00b6 jsPsych is licensed under the MIT license. The MIT License (MIT) Copyright (c) 2019 Joshua R. de Leeuw Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.","title":"License"},{"location":"about/license/#license","text":"jsPsych is licensed under the MIT license. The MIT License (MIT) Copyright (c) 2019 Joshua R. de Leeuw Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.","title":"License"},{"location":"about/support/","text":"Support \u00b6 For questions about jsPsych the preferred method of support is via GitHub 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 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 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 .","title":"Getting Help"},{"location":"about/support/#support","text":"For questions about jsPsych the preferred method of support is via GitHub 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 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 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 .","title":"Support"},{"location":"core_library/jspsych-core/","text":"The jsPsych core library \u00b6 jsPsych.addNodeToEndOfTimeline \u00b6 jsPsych . addNodeToEndOfTimeline ( node_parameters ) Parameters \u00b6 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 \u00b6 None. Description \u00b6 Adds the timeline to the end of the experiment. Example \u00b6 var trial = { type : 'html-keyboard-response' , stimulus : 'This is a new trial.' } var new_timeline = { timeline : [ trial ] } jsPsych . addNodeToEndOfTimeline ( new_timeline ) jsPsych.allTimelineVariables \u00b6 jsPsych . allTimelineVariables () Parameters \u00b6 None. Return value \u00b6 Returns an object with all available timeline variables at this moment in the experiment, represented as key: value pairs. Description \u00b6 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 \u00b6 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 \u00b6 jsPsych . currentTimelineNodeID () Parameters \u00b6 None. Return value \u00b6 Returns the ID of the TimelineNode that is currently active. Description \u00b6 Gets the ID of the active TimelineNode. The ID is a string that follows a specific format: \"0.0\" is the ID of the first top-level TimelineNode \"1.0\" is the ID of the second top-level TimelineNode \"2.0\" is the ID of the third top-level TimelineNode, and so on... If a TimelineNode iterates multiple times (using the loop function, for example), then the iterations are indicated in the second number: \"0.0\" is the ID of the first top-level TimelineNode during the first iteration \"0.1\" is the ID of the first top-level TimelineNode during the second iteration \"0.2\" is the ID of the first top-level TimelineNode during the third iteration, and so on... If TimelineNodes are nested in other TimelineNodes, then the hierarchical structure is shown with \".\" : \"0.0-1.0\" is the ID of the second TimelineNode on the timeline of the first top-level TimelineNode. \"0.0-2.0\" is the ID of the third TimelineNode on the timeline of the first top-level TimelineNode, and so on... The rules about iterations apply throughout the hierarchical ID: \"0.2-1.3\" is the ID of the second TimelineNode, executing for the fourth time, on the timeline of the first top-level TimelineNode, executing for the third time. Example \u00b6 var id = jsPsych . currentTimelineNodeID (); console . log ( 'The current TimelineNode ID is ' + id ); jsPsych.currentTrial \u00b6 jsPsych . currentTrial () Parameters \u00b6 None. Return value \u00b6 Returns the object describing the current trial. The object will contain all of the parameters associated with the current trial. Description \u00b6 Get a description of the current trial Example \u00b6 var trial = jsPsych . currentTrial (); console . log ( 'The current trial is using the ' + trial . type + ' plugin' ); jsPsych.endCurrentTimeline \u00b6 jsPsych . endCurrentTimeline () Parameters \u00b6 None. Return value \u00b6 None. Description \u00b6 Ends the current timeline. If timelines are nested, then only the timeline that contains the current trial is ended. Example \u00b6 End timeline if a particular key is pressed \u00b6 var images = [ \"img/1.gif\" , \"img/2.gif\" , \"img/3.gif\" , \"img/4.gif\" , \"img/5.gif\" , \"img/6.gif\" , \"img/7.gif\" , \"img/8.gif\" , \"img/9.gif\" , \"img/10.gif\" ]; var trials = []; for ( var i = 0 ; i < images . length ; i ++ ) { trials . push ({ stimulus : images [ i ] }); } var block = { type : 'image-keyboard-response' , choices : [ 'y' , 'n' ], prompt : '

Press \"y\" to Continue. Press \"n\" to end this node of the experiment.

' , on_finish : function ( data ) { if ( jsPsych . pluginAPI . compareKeys ( data . response , 'n' )) { jsPsych . endCurrentTimeline (); } }, timeline : trials } var after_block = { type : 'html-keyboard-response' , stimulus : '

The next node

' } jsPsych . init ({ timeline : [ block , after_block ], on_finish : function () { jsPsych . data . displayData (); } }); jsPsych.endExperiment \u00b6 jsPsych . endExperiment ( end_message ) Parameters \u00b6 Parameter Type Description end_message string A message to display on the screen after the experiment is over. Return value \u00b6 None. Description \u00b6 Ends the experiment, skipping all remaining trials. Example \u00b6 End the experiment if a particular response is given \u00b6 var trial = { type : 'image-keyboard-response' , stimulus : 'image1.jpg' , choices : [ 'y' , 'n' ] prompt : '

Press \"y\" to Continue. Press \"n\" to end the experiment

' , on_finish : function ( data ){ if ( jsPsych . pluginAPI . compareKeys ( data . response , \"n\" )){ jsPsych . endExperiment ( 'The experiment was ended by pressing \"n\".' ); } } } jsPsych.finishTrial \u00b6 jsPsych . finishTrial ( data ) Parameters \u00b6 Parameter Type Description data object The data to store for the trial. Return value \u00b6 Returns nothing. Description \u00b6 This method tells jsPsych that the current trial is over. It is used in all of the plugins to end the current trial. When the trial ends a few things happen: The data is stored using jsPsych.data.write() The on_finish callback function is executed for the trial The on_trial_finish callback function is executed The progress bar is updated if it is being displayed The experiment ends if the trial is the last one (and the on_finish callback function is executed). The next trial, if one exists, is started. Example \u00b6 // this code would be in a plugin jsPsych . finishTrial ({ correct_response : true }); jsPsych.getDisplayElement \u00b6 jsPsych . getDisplayElement () Parameters \u00b6 None. Return value \u00b6 Returns the HTML DOM element used for displaying the experiment. Description \u00b6 Get the DOM element that displays the experiment. Example \u00b6 var el = jsPsych . getDisplayElement (); // hide the jsPsych display el . style . visibility = 'hidden' ; jsPsych.getProgressBarCompleted \u00b6 jsPsych . getProgressBarCompleted () Parameters \u00b6 None. Return value \u00b6 Returns a value between 0 and 1 representing how full the progress bar currently is. Description \u00b6 Used to get the current value of the progress bar. Works for automated and manual control. Example \u00b6 var progress_bar_amount = jsPsych . getProgressBarCompleted (); jsPsych.init \u00b6 jsPsych . init ( settings ) Parameters \u00b6 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 . display_element string The ID of an HTML element to display the experiment in. If left blank, jsPsych will use the 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 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 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). Return value \u00b6 Returns nothing. Description \u00b6 This method configures and starts the experiment. Example \u00b6 See any of the plugin examples in the examples folder in the GitHub repository. jsPsych.initSettings \u00b6 jsPsych . initSettings () Parameters \u00b6 None Return value \u00b6 Returns the settings object used to initialize the experiment. Description \u00b6 Gets the object containing the settings for the current experiment. Example \u00b6 var settings = jsPsych . initSettings (); // check the experiment structure console . log ( JSON . stringify ( settings . timeline )); jsPsych.pauseExperiment \u00b6 jsPsych . pauseExperiment () Parameters \u00b6 None. Return value \u00b6 None. Description \u00b6 Pauses the experiment. The experiment will finish the current trial, but will not execute any additional trials until jsPsych.resumeExperiment() is called. Example \u00b6 var trial = { type : 'html-keyboard-response' , stimulus : 'Press p to take a 30 second break. Otherwise, press c to continue immediately.' , choices : [ 'p' , 'c' ], on_finish : function ( data ){ if ( jsPsych . pluginAPI . compareKeys ( data . response , \"p\" )) { jsPsych . pauseExperiment (); setTimeout ( jsPsych . resumeExperiment , 30000 ); } } } jsPsych.progress \u00b6 jsPsych . progress () Parameters \u00b6 None. Return value \u00b6 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. Description \u00b6 This method returns information about the length of the experiment and the subject's current location in the experiment timeline. Example \u00b6 var progress = jsPsych . progress (); alert ( 'You have completed approximately ' + progress . percent_complete + '% of the experiment' ); jsPsych.resumeExperiment \u00b6 jsPsych . resumeExperiment () Parameters \u00b6 None. Return value \u00b6 None. Description \u00b6 Resumes the experiment after a call to jsPsych.pauseExperiment() . If the post trial delay ( post_trial_gap ) has not yet been reached, then the experiment will not continue until the delay is finished. For example, if post_trial_gap was 10,000ms and jsPsych.resumeExperiment() was called 6,000ms after the previous trial finished, then the experiment would not continue for another 4,000ms. Example \u00b6 var trial = { type : 'html-keyboard-response' , stimulus : 'Press p to take a 30 second break. Otherwise, press c to continue immediately.' , choices : [ 'p' , 'c' ], on_finish : function ( data ){ if ( jsPsych . pluginAPI . compareKeys ( data . response , \"p\" )) { jsPsych . pauseExperiment (); setTimeout ( jsPsych . resumeExperiment , 30000 ); } } } jsPsych.setProgressBar \u00b6 jsPsych . setProgressBar ( value ) Parameters \u00b6 Parameter Type Description value numeric Proprotion (between 0 and 1) to fill the progress bar. Return value \u00b6 None. Description \u00b6 Set the progress bar to a custom amount. Proportion must be between 0 and 1. Values larger than 1 are treated as 1. Example \u00b6 jsPsych . setProgressBar ( 0.85 ); jsPsych.startTime \u00b6 jsPsych . startTime () Parameters \u00b6 None. Return value \u00b6 Returns a Date object indicating when the experiment began. Description \u00b6 Get the time that the experiment began. Example \u00b6 var start_time = jsPsych . startTime (); jsPsych.timelineVariable \u00b6 jsPsych . timelineVariable ( variable , call_immediate ) Parameters \u00b6 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 . 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 \u00b6 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 \u00b6 Timeline variables are a powerful technique for generating experiments with repetitive procedures but different parameter values. This function fetches the current value of a particular timeline variable. It must be used in conjunction with a timeline that has timeline variables. See the timeline variable section for details. Examples \u00b6 Standard use as a parameter for a trial \u00b6 var trial = { type : 'image-keyboard-response' , stimulus : jsPsych . timelineVariable ( 'image' ) } var procedure = { timeline : [ trial ], timeline_variables : [ { image : 'face1.png' }, { image : 'face2.png' }, { image : 'face3.png' }, { image : 'face4.png' } ] } Invoking immediately in a function \u00b6 var trial = { type : 'html-keyboard-response' , stimulus : function (){ return \"\" ; } } 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 : var trial = { type : 'html-keyboard-response' , stimulus : function (){ return \"\" ; } } var procedure = { timeline : [ trial ], timeline_variables : [ { image : 'face1.png' }, { image : 'face2.png' }, { image : 'face3.png' }, { image : 'face4.png' } ] } jsPsych.totalTime \u00b6 jsPsych . totalTime () Parameters \u00b6 None. Return value \u00b6 Returns a numeric value indicating the number of milliseconds since jsPsych.init was called. Description \u00b6 Gets the total time the subject has been in the experiment. Example \u00b6 var time = jsPsych . totalTime (); console . log ( time ); jsPsych.version \u00b6 jsPsych . version () Parameters \u00b6 None. Return value \u00b6 Returns the version number as a string. Description \u00b6 Gets the version of jsPsych. Example \u00b6 var version = jsPsych . version (); console . log ( version );","title":"jsPsych"},{"location":"core_library/jspsych-core/#the-jspsych-core-library","text":"","title":"The jsPsych core library"},{"location":"core_library/jspsych-core/#jspsychaddnodetoendoftimeline","text":"jsPsych . addNodeToEndOfTimeline ( node_parameters )","title":"jsPsych.addNodeToEndOfTimeline"},{"location":"core_library/jspsych-core/#parameters","text":"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.","title":"Parameters"},{"location":"core_library/jspsych-core/#return-value","text":"None.","title":"Return value"},{"location":"core_library/jspsych-core/#description","text":"Adds the timeline to the end of the experiment.","title":"Description"},{"location":"core_library/jspsych-core/#example","text":"var trial = { type : 'html-keyboard-response' , stimulus : 'This is a new trial.' } var new_timeline = { timeline : [ trial ] } jsPsych . addNodeToEndOfTimeline ( new_timeline )","title":"Example"},{"location":"core_library/jspsych-core/#jspsychalltimelinevariables","text":"jsPsych . allTimelineVariables ()","title":"jsPsych.allTimelineVariables"},{"location":"core_library/jspsych-core/#parameters_1","text":"None.","title":"Parameters"},{"location":"core_library/jspsych-core/#return-value_1","text":"Returns an object with all available timeline variables at this moment in the experiment, represented as key: value pairs.","title":"Return value"},{"location":"core_library/jspsych-core/#description_1","text":"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.","title":"Description"},{"location":"core_library/jspsych-core/#example_1","text":"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 ()) } }","title":"Example"},{"location":"core_library/jspsych-core/#jspsychcurrenttimelinenodeid","text":"jsPsych . currentTimelineNodeID ()","title":"jsPsych.currentTimelineNodeID"},{"location":"core_library/jspsych-core/#parameters_2","text":"None.","title":"Parameters"},{"location":"core_library/jspsych-core/#return-value_2","text":"Returns the ID of the TimelineNode that is currently active.","title":"Return value"},{"location":"core_library/jspsych-core/#description_2","text":"Gets the ID of the active TimelineNode. The ID is a string that follows a specific format: \"0.0\" is the ID of the first top-level TimelineNode \"1.0\" is the ID of the second top-level TimelineNode \"2.0\" is the ID of the third top-level TimelineNode, and so on... If a TimelineNode iterates multiple times (using the loop function, for example), then the iterations are indicated in the second number: \"0.0\" is the ID of the first top-level TimelineNode during the first iteration \"0.1\" is the ID of the first top-level TimelineNode during the second iteration \"0.2\" is the ID of the first top-level TimelineNode during the third iteration, and so on... If TimelineNodes are nested in other TimelineNodes, then the hierarchical structure is shown with \".\" : \"0.0-1.0\" is the ID of the second TimelineNode on the timeline of the first top-level TimelineNode. \"0.0-2.0\" is the ID of the third TimelineNode on the timeline of the first top-level TimelineNode, and so on... The rules about iterations apply throughout the hierarchical ID: \"0.2-1.3\" is the ID of the second TimelineNode, executing for the fourth time, on the timeline of the first top-level TimelineNode, executing for the third time.","title":"Description"},{"location":"core_library/jspsych-core/#example_2","text":"var id = jsPsych . currentTimelineNodeID (); console . log ( 'The current TimelineNode ID is ' + id );","title":"Example"},{"location":"core_library/jspsych-core/#jspsychcurrenttrial","text":"jsPsych . currentTrial ()","title":"jsPsych.currentTrial"},{"location":"core_library/jspsych-core/#parameters_3","text":"None.","title":"Parameters"},{"location":"core_library/jspsych-core/#return-value_3","text":"Returns the object describing the current trial. The object will contain all of the parameters associated with the current trial.","title":"Return value"},{"location":"core_library/jspsych-core/#description_3","text":"Get a description of the current trial","title":"Description"},{"location":"core_library/jspsych-core/#example_3","text":"var trial = jsPsych . currentTrial (); console . log ( 'The current trial is using the ' + trial . type + ' plugin' );","title":"Example"},{"location":"core_library/jspsych-core/#jspsychendcurrenttimeline","text":"jsPsych . endCurrentTimeline ()","title":"jsPsych.endCurrentTimeline"},{"location":"core_library/jspsych-core/#parameters_4","text":"None.","title":"Parameters"},{"location":"core_library/jspsych-core/#return-value_4","text":"None.","title":"Return value"},{"location":"core_library/jspsych-core/#description_4","text":"Ends the current timeline. If timelines are nested, then only the timeline that contains the current trial is ended.","title":"Description"},{"location":"core_library/jspsych-core/#example_4","text":"","title":"Example"},{"location":"core_library/jspsych-core/#end-timeline-if-a-particular-key-is-pressed","text":"var images = [ \"img/1.gif\" , \"img/2.gif\" , \"img/3.gif\" , \"img/4.gif\" , \"img/5.gif\" , \"img/6.gif\" , \"img/7.gif\" , \"img/8.gif\" , \"img/9.gif\" , \"img/10.gif\" ]; var trials = []; for ( var i = 0 ; i < images . length ; i ++ ) { trials . push ({ stimulus : images [ i ] }); } var block = { type : 'image-keyboard-response' , choices : [ 'y' , 'n' ], prompt : '

Press \"y\" to Continue. Press \"n\" to end this node of the experiment.

' , on_finish : function ( data ) { if ( jsPsych . pluginAPI . compareKeys ( data . response , 'n' )) { jsPsych . endCurrentTimeline (); } }, timeline : trials } var after_block = { type : 'html-keyboard-response' , stimulus : '

The next node

' } jsPsych . init ({ timeline : [ block , after_block ], on_finish : function () { jsPsych . data . displayData (); } });","title":"End timeline if a particular key is pressed"},{"location":"core_library/jspsych-core/#jspsychendexperiment","text":"jsPsych . endExperiment ( end_message )","title":"jsPsych.endExperiment"},{"location":"core_library/jspsych-core/#parameters_5","text":"Parameter Type Description end_message string A message to display on the screen after the experiment is over.","title":"Parameters"},{"location":"core_library/jspsych-core/#return-value_5","text":"None.","title":"Return value"},{"location":"core_library/jspsych-core/#description_5","text":"Ends the experiment, skipping all remaining trials.","title":"Description"},{"location":"core_library/jspsych-core/#example_5","text":"","title":"Example"},{"location":"core_library/jspsych-core/#end-the-experiment-if-a-particular-response-is-given","text":"var trial = { type : 'image-keyboard-response' , stimulus : 'image1.jpg' , choices : [ 'y' , 'n' ] prompt : '

Press \"y\" to Continue. Press \"n\" to end the experiment

' , on_finish : function ( data ){ if ( jsPsych . pluginAPI . compareKeys ( data . response , \"n\" )){ jsPsych . endExperiment ( 'The experiment was ended by pressing \"n\".' ); } } }","title":"End the experiment if a particular response is given"},{"location":"core_library/jspsych-core/#jspsychfinishtrial","text":"jsPsych . finishTrial ( data )","title":"jsPsych.finishTrial"},{"location":"core_library/jspsych-core/#parameters_6","text":"Parameter Type Description data object The data to store for the trial.","title":"Parameters"},{"location":"core_library/jspsych-core/#return-value_6","text":"Returns nothing.","title":"Return value"},{"location":"core_library/jspsych-core/#description_6","text":"This method tells jsPsych that the current trial is over. It is used in all of the plugins to end the current trial. When the trial ends a few things happen: The data is stored using jsPsych.data.write() The on_finish callback function is executed for the trial The on_trial_finish callback function is executed The progress bar is updated if it is being displayed The experiment ends if the trial is the last one (and the on_finish callback function is executed). The next trial, if one exists, is started.","title":"Description"},{"location":"core_library/jspsych-core/#example_6","text":"// this code would be in a plugin jsPsych . finishTrial ({ correct_response : true });","title":"Example"},{"location":"core_library/jspsych-core/#jspsychgetdisplayelement","text":"jsPsych . getDisplayElement ()","title":"jsPsych.getDisplayElement"},{"location":"core_library/jspsych-core/#parameters_7","text":"None.","title":"Parameters"},{"location":"core_library/jspsych-core/#return-value_7","text":"Returns the HTML DOM element used for displaying the experiment.","title":"Return value"},{"location":"core_library/jspsych-core/#description_7","text":"Get the DOM element that displays the experiment.","title":"Description"},{"location":"core_library/jspsych-core/#example_7","text":"var el = jsPsych . getDisplayElement (); // hide the jsPsych display el . style . visibility = 'hidden' ;","title":"Example"},{"location":"core_library/jspsych-core/#jspsychgetprogressbarcompleted","text":"jsPsych . getProgressBarCompleted ()","title":"jsPsych.getProgressBarCompleted"},{"location":"core_library/jspsych-core/#parameters_8","text":"None.","title":"Parameters"},{"location":"core_library/jspsych-core/#return-value_8","text":"Returns a value between 0 and 1 representing how full the progress bar currently is.","title":"Return value"},{"location":"core_library/jspsych-core/#description_8","text":"Used to get the current value of the progress bar. Works for automated and manual control.","title":"Description"},{"location":"core_library/jspsych-core/#example_8","text":"var progress_bar_amount = jsPsych . getProgressBarCompleted ();","title":"Example"},{"location":"core_library/jspsych-core/#jspsychinit","text":"jsPsych . init ( settings )","title":"jsPsych.init"},{"location":"core_library/jspsych-core/#parameters_9","text":"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 . display_element string The ID of an HTML element to display the experiment in. If left blank, jsPsych will use the 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 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 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).","title":"Parameters"},{"location":"core_library/jspsych-core/#return-value_9","text":"Returns nothing.","title":"Return value"},{"location":"core_library/jspsych-core/#description_9","text":"This method configures and starts the experiment.","title":"Description"},{"location":"core_library/jspsych-core/#example_9","text":"See any of the plugin examples in the examples folder in the GitHub repository.","title":"Example"},{"location":"core_library/jspsych-core/#jspsychinitsettings","text":"jsPsych . initSettings ()","title":"jsPsych.initSettings"},{"location":"core_library/jspsych-core/#parameters_10","text":"None","title":"Parameters"},{"location":"core_library/jspsych-core/#return-value_10","text":"Returns the settings object used to initialize the experiment.","title":"Return value"},{"location":"core_library/jspsych-core/#description_10","text":"Gets the object containing the settings for the current experiment.","title":"Description"},{"location":"core_library/jspsych-core/#example_10","text":"var settings = jsPsych . initSettings (); // check the experiment structure console . log ( JSON . stringify ( settings . timeline ));","title":"Example"},{"location":"core_library/jspsych-core/#jspsychpauseexperiment","text":"jsPsych . pauseExperiment ()","title":"jsPsych.pauseExperiment"},{"location":"core_library/jspsych-core/#parameters_11","text":"None.","title":"Parameters"},{"location":"core_library/jspsych-core/#return-value_11","text":"None.","title":"Return value"},{"location":"core_library/jspsych-core/#description_11","text":"Pauses the experiment. The experiment will finish the current trial, but will not execute any additional trials until jsPsych.resumeExperiment() is called.","title":"Description"},{"location":"core_library/jspsych-core/#example_11","text":"var trial = { type : 'html-keyboard-response' , stimulus : 'Press p to take a 30 second break. Otherwise, press c to continue immediately.' , choices : [ 'p' , 'c' ], on_finish : function ( data ){ if ( jsPsych . pluginAPI . compareKeys ( data . response , \"p\" )) { jsPsych . pauseExperiment (); setTimeout ( jsPsych . resumeExperiment , 30000 ); } } }","title":"Example"},{"location":"core_library/jspsych-core/#jspsychprogress","text":"jsPsych . progress ()","title":"jsPsych.progress"},{"location":"core_library/jspsych-core/#parameters_12","text":"None.","title":"Parameters"},{"location":"core_library/jspsych-core/#return-value_12","text":"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.","title":"Return value"},{"location":"core_library/jspsych-core/#description_12","text":"This method returns information about the length of the experiment and the subject's current location in the experiment timeline.","title":"Description"},{"location":"core_library/jspsych-core/#example_12","text":"var progress = jsPsych . progress (); alert ( 'You have completed approximately ' + progress . percent_complete + '% of the experiment' );","title":"Example"},{"location":"core_library/jspsych-core/#jspsychresumeexperiment","text":"jsPsych . resumeExperiment ()","title":"jsPsych.resumeExperiment"},{"location":"core_library/jspsych-core/#parameters_13","text":"None.","title":"Parameters"},{"location":"core_library/jspsych-core/#return-value_13","text":"None.","title":"Return value"},{"location":"core_library/jspsych-core/#description_13","text":"Resumes the experiment after a call to jsPsych.pauseExperiment() . If the post trial delay ( post_trial_gap ) has not yet been reached, then the experiment will not continue until the delay is finished. For example, if post_trial_gap was 10,000ms and jsPsych.resumeExperiment() was called 6,000ms after the previous trial finished, then the experiment would not continue for another 4,000ms.","title":"Description"},{"location":"core_library/jspsych-core/#example_13","text":"var trial = { type : 'html-keyboard-response' , stimulus : 'Press p to take a 30 second break. Otherwise, press c to continue immediately.' , choices : [ 'p' , 'c' ], on_finish : function ( data ){ if ( jsPsych . pluginAPI . compareKeys ( data . response , \"p\" )) { jsPsych . pauseExperiment (); setTimeout ( jsPsych . resumeExperiment , 30000 ); } } }","title":"Example"},{"location":"core_library/jspsych-core/#jspsychsetprogressbar","text":"jsPsych . setProgressBar ( value )","title":"jsPsych.setProgressBar"},{"location":"core_library/jspsych-core/#parameters_14","text":"Parameter Type Description value numeric Proprotion (between 0 and 1) to fill the progress bar.","title":"Parameters"},{"location":"core_library/jspsych-core/#return-value_14","text":"None.","title":"Return value"},{"location":"core_library/jspsych-core/#description_14","text":"Set the progress bar to a custom amount. Proportion must be between 0 and 1. Values larger than 1 are treated as 1.","title":"Description"},{"location":"core_library/jspsych-core/#example_14","text":"jsPsych . setProgressBar ( 0.85 );","title":"Example"},{"location":"core_library/jspsych-core/#jspsychstarttime","text":"jsPsych . startTime ()","title":"jsPsych.startTime"},{"location":"core_library/jspsych-core/#parameters_15","text":"None.","title":"Parameters"},{"location":"core_library/jspsych-core/#return-value_15","text":"Returns a Date object indicating when the experiment began.","title":"Return value"},{"location":"core_library/jspsych-core/#description_15","text":"Get the time that the experiment began.","title":"Description"},{"location":"core_library/jspsych-core/#example_15","text":"var start_time = jsPsych . startTime ();","title":"Example"},{"location":"core_library/jspsych-core/#jspsychtimelinevariable","text":"jsPsych . timelineVariable ( variable , call_immediate )","title":"jsPsych.timelineVariable"},{"location":"core_library/jspsych-core/#parameters_16","text":"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 . 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.","title":"Parameters"},{"location":"core_library/jspsych-core/#return-value_16","text":"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.","title":"Return value"},{"location":"core_library/jspsych-core/#description_16","text":"Timeline variables are a powerful technique for generating experiments with repetitive procedures but different parameter values. This function fetches the current value of a particular timeline variable. It must be used in conjunction with a timeline that has timeline variables. See the timeline variable section for details.","title":"Description"},{"location":"core_library/jspsych-core/#examples","text":"","title":"Examples"},{"location":"core_library/jspsych-core/#standard-use-as-a-parameter-for-a-trial","text":"var trial = { type : 'image-keyboard-response' , stimulus : jsPsych . timelineVariable ( 'image' ) } var procedure = { timeline : [ trial ], timeline_variables : [ { image : 'face1.png' }, { image : 'face2.png' }, { image : 'face3.png' }, { image : 'face4.png' } ] }","title":"Standard use as a parameter for a trial"},{"location":"core_library/jspsych-core/#invoking-immediately-in-a-function","text":"var trial = { type : 'html-keyboard-response' , stimulus : function (){ return \"\" ; } } 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 : var trial = { type : 'html-keyboard-response' , stimulus : function (){ return \"\" ; } } var procedure = { timeline : [ trial ], timeline_variables : [ { image : 'face1.png' }, { image : 'face2.png' }, { image : 'face3.png' }, { image : 'face4.png' } ] }","title":"Invoking immediately in a function"},{"location":"core_library/jspsych-core/#jspsychtotaltime","text":"jsPsych . totalTime ()","title":"jsPsych.totalTime"},{"location":"core_library/jspsych-core/#parameters_17","text":"None.","title":"Parameters"},{"location":"core_library/jspsych-core/#return-value_17","text":"Returns a numeric value indicating the number of milliseconds since jsPsych.init was called.","title":"Return value"},{"location":"core_library/jspsych-core/#description_17","text":"Gets the total time the subject has been in the experiment.","title":"Description"},{"location":"core_library/jspsych-core/#example_16","text":"var time = jsPsych . totalTime (); console . log ( time );","title":"Example"},{"location":"core_library/jspsych-core/#jspsychversion","text":"jsPsych . version ()","title":"jsPsych.version"},{"location":"core_library/jspsych-core/#parameters_18","text":"None.","title":"Parameters"},{"location":"core_library/jspsych-core/#return-value_18","text":"Returns the version number as a string.","title":"Return value"},{"location":"core_library/jspsych-core/#description_18","text":"Gets the version of jsPsych.","title":"Description"},{"location":"core_library/jspsych-core/#example_17","text":"var version = jsPsych . version (); console . log ( version );","title":"Example"},{"location":"core_library/jspsych-data/","text":"jsPsych.data \u00b6 The jsPsych.data module contains functions for interacting with the data generated by jsPsych plugins. jsPsych.data.addProperties \u00b6 jsPsych . data . addProperties ( properties ) Parameters \u00b6 Parameter Type Description properties object Object of key: value pairs to add to the data. Return value \u00b6 Returns nothing. Description \u00b6 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 \u00b6 Assigning a subject ID and condition code \u00b6 jsPsych . data . addProperties ({ subject : 1 , condition : 'control' }); jsPsych.data.displayData \u00b6 jsPsych . data . displayData ( format ) Parameters \u00b6 Parameter Type Description format string Specifies whether to display the data in 'csv' or 'json' format. Return value \u00b6 Returns nothing. Description \u00b6 Outputs all of the data collected in the experiment to the screen in either JSON or CSV format. This is a useful method for quick debugging when developing an experiment. Examples \u00b6 Using the on_finish callback function to show data at the end of the experiment \u00b6 jsPsych . init ({ experiment_structure : exp , on_finish : function () { jsPsych . data . displayData ( 'csv' ); } }) jsPsych.data.get \u00b6 jsPsych.data.get() Parameters \u00b6 None. Return value \u00b6 Returns the data collection of all data generated by the experiment. Description \u00b6 This function is the standard starting point for accessing the data generated by the experiment. It returns a DataCollection object, which has several methods that can be used to further filter, aggregate, and view the data. These methods are described under the DataCollection section on this page. Example \u00b6 // select all trials var all_data = jsPsych . data . get (); // get csv representation of data and log to console console . log ( all_data . csv ()); jsPsych.data.getDataByTimelineNode \u00b6 jsPsych . data . getDataByTimelineNode ( node_id ) Parameters \u00b6 Parameter Type Description node_id string The id of the TimelineNodes to get data from. Return value \u00b6 Returns a DataCollection of all of the data generated in a specified TimelineNode. Description \u00b6 Get all the data generated by a specified Timeline. Example \u00b6 var current_node_id = jsPsych . currentTimelineNodeID (); var data_from_current_node = jsPsych . data . getDataByTimelineNode ( current_node_id ); jsPsych.data.getInteractionData \u00b6 jsPsych . data . getInteractionData () Parameters \u00b6 None. Return value \u00b6 Returns a DataCollection object with all of the interaction events. Description \u00b6 jsPsych automatically records a few different kinds of user interaction events. blur events occur when the user clicks on another window or tab during the experiment, indicating that they are no longer interacting with the experiment. focus events occur when the user clicks on the experiment window after having clicked somewhere else first (i.e., generated a blur event). fullscreenenter and fullscreenexit events are triggered by the browser entering and exiting fullscreen mode. However, fullscreenenter events only occur when the script switches the browser to fullscreen mode, e.g., with the jspsych-fullscreen plugin. Manually entering fullscreen mode does not trigger this event. fullscreenexit events occur whether the user manually exits fullscreen mode or the script exits fullscreen mode. This method returns the DataCollection containing all interaction events. This is useful for tracking whether the participant completed the task without diverting attention to other windows. Events are in the form: { type : 'focus' or 'blur' or 'fullscreenenter' or 'fullscreenexit' , trial : 10 , // the trial number when the event happened time : 13042 // total time elapsed since the start of the experiment } Example \u00b6 var interaction_data = jsPsych . data . getInteractionData (); // log data to console in json format console . log ( interaction_data . json ()); jsPsych.data.getLastTimelineData \u00b6 jsPsych . data . getLastTimelineData () Return value \u00b6 Returns a DataCollection. Description \u00b6 Gets all of the data generated in the same timeline as the last trial. Example \u00b6 var lasttimelinedata = jsPsych . data . getLastTimelineData (); jsPsych.data.getLastTrialData \u00b6 jsPsych . data . getLastTrialData () Return value \u00b6 Returns a DataCollection. Description \u00b6 Gets the data collection containing all data generated by the last trial. Example \u00b6 var lasttrialdata = jsPsych . data . getLastTrialData (); jsPsych.data.getURLVariable \u00b6 jsPsych . data . getURLVariable ( var_name ) Parameters \u00b6 Parameter Type Description var_name string Which variable to get the value of. Return value \u00b6 Returns the value of a variable passed in through the query string. Description \u00b6 For extracting a particular variable passed in through a URL query string. Example \u00b6 // 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 \u00b6 jsPsych . data . urlVariables () Return value \u00b6 Returns an object (associative array) of the variables in the URL query string. Description \u00b6 For extracting variables passed in through a URL query string. Example \u00b6 // 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 \u00b6 jsPsych . data . write ( data_object ) Parameters \u00b6 Parameter Type Description data_object object Object of key: value pairs to store in jsPsych's data storage as a trial. Return value \u00b6 Returns nothing. Description \u00b6 This method is used by jsPsych.finishTrial for writing data. You should probably not use it to add data. Instead use jsPsych.data.addProperties . Example \u00b6 // don't use this! data should only be written once per trial. use jsPsych.finishTrial to save data. var trial_data = { correct : true , rt : 487 } jsPsych . data . write ( trial_data ); DataCollection \u00b6 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() \u00b6 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. jsPsych . data . get (). addToAll ({ subject_id : 123 , condition : 'control' }); .addToLast() \u00b6 Adds a set of properties to the last trial in the DataCollection. jsPsych . data . get (). addToLast ({ success : true }); .count() \u00b6 Counts the number of trials in the DataCollection. jsPsych . data . get (). count () .csv() \u00b6 Generates a CSV string representing all of the data in the DataCollection. console . log ( jsPsych . data . get (). csv ()); .filter() \u00b6 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. 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. // 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. // 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. // count the number of correct trials in block 1 var block_1_correct = jsPsych . data . get (). filter ({ block : 1 , correct : true }). count (); .filterCustom() \u00b6 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. // 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 ; }). count () .first() / .last() \u00b6 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. 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 ); .ignore() \u00b6 Returns a DataCollection with all instances of a particular key removed from the dataset. // 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 ()); .join() \u00b6 Appends one DataCollection onto another and returns the combined collection. // 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 }); var dc2 = jsPsych . data . get (). filterCustom ( function ( trial ){ return trial . rt > 200 }); var data = dc1 . join ( dc2 ); .json() \u00b6 Generates a JSON string representing all of the data in the DataCollection. console . log ( jsPsych . data . get (). json ()); .localSave() \u00b6 Saves a CSV or JSON file on the computer running the experiment. If conducting an online experiment, this will download the file onto the subject's computer, and is therefore not a recommended data storage solution for online data collection. Warning: This function may not behave correctly in older browsers. Upgrading to the latest version of any major web browser should solve the problem. // first argument is the format, second is the filename. // the format can be either 'csv' or 'json'. jsPsych . data . get (). localSave ( 'csv' , 'mydata.csv' ); .push() \u00b6 Add a new entry to the DataCollection. This method is mostly used internally, and you shouldn't need to call it under normal circumstances. var data = { correct : true , rt : 500 } jsPsych . data . get (). push ( data ); .readOnly() \u00b6 Creates a copy of the DataCollection so that any modification of the values in the DataCollection will not affect the original. // this line edits the rt property of the first trial jsPsych . data . get (). first ( 1 ). values ()[ 0 ]. rt = 100 ; // readOnly creates a copy that can be modified without affecting the original jsPsych . data . get (). first ( 1 ). values ()[ 0 ]. rt // outputs 100 jsPsych . data . get (). readOnly (). first ( 1 ). values ()[ 0 ]. rt = 200 jsPsych . data . get (). first ( 1 ). values ()[ 0 ]. rt // still outputs 100 .select() \u00b6 Returns a DataColumn object (see documentation below) of a single property from a DataCollection object. var rt_data = jsPsych . data . get (). select ( 'rt' ); rt_data . mean () .uniqueNames() \u00b6 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. console . log ( jsPsych . data . get (). uniqueNames ()); .values() \u00b6 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. var raw_data = jsPsych . data . get (). values (); // was response in first trial correct? if ( raw_data [ 0 ]. correct ){ console . log ( 'correct!' ); } else { console . log ( 'incorrect.' ); } DataColumn \u00b6 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. .all() \u00b6 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. // 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 ; }); .count() \u00b6 Counts the number of values in the DataColumn. // count how many response times there are jsPsych . data . get (). select ( 'rt' ). count (); .frequencies() \u00b6 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. // get frequencies of correct and incorrect responses jsPsych . data . get (). select ( 'correct' ). frequencies (); .max() / .min() \u00b6 Returns the maximum or minimum value in a DataColumn. jsPsych . data . get (). select ( 'rt' ). max (); jsPsych . data . get (). select ( 'rt' ). min (); .mean() \u00b6 Returns the average of all the values in a DataColumn. jsPsych . data . get (). select ( 'rt' ). mean (); .median() \u00b6 Returns the median of all the values in a DataColumn. jsPsych . data . get (). select ( 'rt' ). median (); .sd() \u00b6 Returns the standard deviation of the values in a DataColumn. jsPsych . data . get (). select ( 'rt' ). sd (); .subset() \u00b6 Filters the DataColumn to include only values that return true when passed through the specified function. // below results will be less than 200. jsPsych . data . get (). select ( 'rt' ). subset ( function ( x ){ return x < 200 ; }). max (); .sum() \u00b6 Returns the sum of the values in a DataColumn. jsPsych . data . get (). select ( 'rt' ). sum (); .values \u00b6 The raw array of values in the DataColumn. // note that this is not a function call. jsPsych . data . get (). select ( 'rt' ). values ; .variance() \u00b6 Returns the variance of the values in a DataColumn. jsPsych . data . get (). select ( 'rt' ). variance ();","title":"jsPsych.data"},{"location":"core_library/jspsych-data/#jspsychdata","text":"The jsPsych.data module contains functions for interacting with the data generated by jsPsych plugins.","title":"jsPsych.data"},{"location":"core_library/jspsych-data/#jspsychdataaddproperties","text":"jsPsych . data . addProperties ( properties )","title":"jsPsych.data.addProperties"},{"location":"core_library/jspsych-data/#parameters","text":"Parameter Type Description properties object Object of key: value pairs to add to the data.","title":"Parameters"},{"location":"core_library/jspsych-data/#return-value","text":"Returns nothing.","title":"Return value"},{"location":"core_library/jspsych-data/#description","text":"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.","title":"Description"},{"location":"core_library/jspsych-data/#examples","text":"","title":"Examples"},{"location":"core_library/jspsych-data/#assigning-a-subject-id-and-condition-code","text":"jsPsych . data . addProperties ({ subject : 1 , condition : 'control' });","title":"Assigning a subject ID and condition code"},{"location":"core_library/jspsych-data/#jspsychdatadisplaydata","text":"jsPsych . data . displayData ( format )","title":"jsPsych.data.displayData"},{"location":"core_library/jspsych-data/#parameters_1","text":"Parameter Type Description format string Specifies whether to display the data in 'csv' or 'json' format.","title":"Parameters"},{"location":"core_library/jspsych-data/#return-value_1","text":"Returns nothing.","title":"Return value"},{"location":"core_library/jspsych-data/#description_1","text":"Outputs all of the data collected in the experiment to the screen in either JSON or CSV format. This is a useful method for quick debugging when developing an experiment.","title":"Description"},{"location":"core_library/jspsych-data/#examples_1","text":"","title":"Examples"},{"location":"core_library/jspsych-data/#using-the-on_finish-callback-function-to-show-data-at-the-end-of-the-experiment","text":"jsPsych . init ({ experiment_structure : exp , on_finish : function () { jsPsych . data . displayData ( 'csv' ); } })","title":"Using the on_finish callback function to show data at the end of the experiment"},{"location":"core_library/jspsych-data/#jspsychdataget","text":"jsPsych.data.get()","title":"jsPsych.data.get"},{"location":"core_library/jspsych-data/#parameters_2","text":"None.","title":"Parameters"},{"location":"core_library/jspsych-data/#return-value_2","text":"Returns the data collection of all data generated by the experiment.","title":"Return value"},{"location":"core_library/jspsych-data/#description_2","text":"This function is the standard starting point for accessing the data generated by the experiment. It returns a DataCollection object, which has several methods that can be used to further filter, aggregate, and view the data. These methods are described under the DataCollection section on this page.","title":"Description"},{"location":"core_library/jspsych-data/#example","text":"// select all trials var all_data = jsPsych . data . get (); // get csv representation of data and log to console console . log ( all_data . csv ());","title":"Example"},{"location":"core_library/jspsych-data/#jspsychdatagetdatabytimelinenode","text":"jsPsych . data . getDataByTimelineNode ( node_id )","title":"jsPsych.data.getDataByTimelineNode"},{"location":"core_library/jspsych-data/#parameters_3","text":"Parameter Type Description node_id string The id of the TimelineNodes to get data from.","title":"Parameters"},{"location":"core_library/jspsych-data/#return-value_3","text":"Returns a DataCollection of all of the data generated in a specified TimelineNode.","title":"Return value"},{"location":"core_library/jspsych-data/#description_3","text":"Get all the data generated by a specified Timeline.","title":"Description"},{"location":"core_library/jspsych-data/#example_1","text":"var current_node_id = jsPsych . currentTimelineNodeID (); var data_from_current_node = jsPsych . data . getDataByTimelineNode ( current_node_id );","title":"Example"},{"location":"core_library/jspsych-data/#jspsychdatagetinteractiondata","text":"jsPsych . data . getInteractionData ()","title":"jsPsych.data.getInteractionData"},{"location":"core_library/jspsych-data/#parameters_4","text":"None.","title":"Parameters"},{"location":"core_library/jspsych-data/#return-value_4","text":"Returns a DataCollection object with all of the interaction events.","title":"Return value"},{"location":"core_library/jspsych-data/#description_4","text":"jsPsych automatically records a few different kinds of user interaction events. blur events occur when the user clicks on another window or tab during the experiment, indicating that they are no longer interacting with the experiment. focus events occur when the user clicks on the experiment window after having clicked somewhere else first (i.e., generated a blur event). fullscreenenter and fullscreenexit events are triggered by the browser entering and exiting fullscreen mode. However, fullscreenenter events only occur when the script switches the browser to fullscreen mode, e.g., with the jspsych-fullscreen plugin. Manually entering fullscreen mode does not trigger this event. fullscreenexit events occur whether the user manually exits fullscreen mode or the script exits fullscreen mode. This method returns the DataCollection containing all interaction events. This is useful for tracking whether the participant completed the task without diverting attention to other windows. Events are in the form: { type : 'focus' or 'blur' or 'fullscreenenter' or 'fullscreenexit' , trial : 10 , // the trial number when the event happened time : 13042 // total time elapsed since the start of the experiment }","title":"Description"},{"location":"core_library/jspsych-data/#example_2","text":"var interaction_data = jsPsych . data . getInteractionData (); // log data to console in json format console . log ( interaction_data . json ());","title":"Example"},{"location":"core_library/jspsych-data/#jspsychdatagetlasttimelinedata","text":"jsPsych . data . getLastTimelineData ()","title":"jsPsych.data.getLastTimelineData"},{"location":"core_library/jspsych-data/#return-value_5","text":"Returns a DataCollection.","title":"Return value"},{"location":"core_library/jspsych-data/#description_5","text":"Gets all of the data generated in the same timeline as the last trial.","title":"Description"},{"location":"core_library/jspsych-data/#example_3","text":"var lasttimelinedata = jsPsych . data . getLastTimelineData ();","title":"Example"},{"location":"core_library/jspsych-data/#jspsychdatagetlasttrialdata","text":"jsPsych . data . getLastTrialData ()","title":"jsPsych.data.getLastTrialData"},{"location":"core_library/jspsych-data/#return-value_6","text":"Returns a DataCollection.","title":"Return value"},{"location":"core_library/jspsych-data/#description_6","text":"Gets the data collection containing all data generated by the last trial.","title":"Description"},{"location":"core_library/jspsych-data/#example_4","text":"var lasttrialdata = jsPsych . data . getLastTrialData ();","title":"Example"},{"location":"core_library/jspsych-data/#jspsychdatageturlvariable","text":"jsPsych . data . getURLVariable ( var_name )","title":"jsPsych.data.getURLVariable"},{"location":"core_library/jspsych-data/#parameters_5","text":"Parameter Type Description var_name string Which variable to get the value of.","title":"Parameters"},{"location":"core_library/jspsych-data/#return-value_7","text":"Returns the value of a variable passed in through the query string.","title":"Return value"},{"location":"core_library/jspsych-data/#description_7","text":"For extracting a particular variable passed in through a URL query string.","title":"Description"},{"location":"core_library/jspsych-data/#example_5","text":"// 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\"","title":"Example"},{"location":"core_library/jspsych-data/#jspsychdataurlvariables","text":"jsPsych . data . urlVariables ()","title":"jsPsych.data.urlVariables"},{"location":"core_library/jspsych-data/#return-value_8","text":"Returns an object (associative array) of the variables in the URL query string.","title":"Return value"},{"location":"core_library/jspsych-data/#description_8","text":"For extracting variables passed in through a URL query string.","title":"Description"},{"location":"core_library/jspsych-data/#example_6","text":"// 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\"","title":"Example"},{"location":"core_library/jspsych-data/#jspsychdatawrite","text":"jsPsych . data . write ( data_object )","title":"jsPsych.data.write"},{"location":"core_library/jspsych-data/#parameters_6","text":"Parameter Type Description data_object object Object of key: value pairs to store in jsPsych's data storage as a trial.","title":"Parameters"},{"location":"core_library/jspsych-data/#return-value_9","text":"Returns nothing.","title":"Return value"},{"location":"core_library/jspsych-data/#description_9","text":"This method is used by jsPsych.finishTrial for writing data. You should probably not use it to add data. Instead use jsPsych.data.addProperties .","title":"Description"},{"location":"core_library/jspsych-data/#example_7","text":"// don't use this! data should only be written once per trial. use jsPsych.finishTrial to save data. var trial_data = { correct : true , rt : 487 } jsPsych . data . write ( trial_data );","title":"Example"},{"location":"core_library/jspsych-data/#datacollection","text":"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.","title":"DataCollection"},{"location":"core_library/jspsych-data/#addtoall","text":"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. jsPsych . data . get (). addToAll ({ subject_id : 123 , condition : 'control' });","title":".addToAll()"},{"location":"core_library/jspsych-data/#addtolast","text":"Adds a set of properties to the last trial in the DataCollection. jsPsych . data . get (). addToLast ({ success : true });","title":".addToLast()"},{"location":"core_library/jspsych-data/#count","text":"Counts the number of trials in the DataCollection. jsPsych . data . get (). count ()","title":".count()"},{"location":"core_library/jspsych-data/#csv","text":"Generates a CSV string representing all of the data in the DataCollection. console . log ( jsPsych . data . get (). csv ());","title":".csv()"},{"location":"core_library/jspsych-data/#filter","text":"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. 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. // 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. // 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. // count the number of correct trials in block 1 var block_1_correct = jsPsych . data . get (). filter ({ block : 1 , correct : true }). count ();","title":".filter()"},{"location":"core_library/jspsych-data/#filtercustom","text":"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. // 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 ; }). count ()","title":".filterCustom()"},{"location":"core_library/jspsych-data/#first-last","text":"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. 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 );","title":".first() / .last()"},{"location":"core_library/jspsych-data/#ignore","text":"Returns a DataCollection with all instances of a particular key removed from the dataset. // 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 ());","title":".ignore()"},{"location":"core_library/jspsych-data/#join","text":"Appends one DataCollection onto another and returns the combined collection. // 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 }); var dc2 = jsPsych . data . get (). filterCustom ( function ( trial ){ return trial . rt > 200 }); var data = dc1 . join ( dc2 );","title":".join()"},{"location":"core_library/jspsych-data/#json","text":"Generates a JSON string representing all of the data in the DataCollection. console . log ( jsPsych . data . get (). json ());","title":".json()"},{"location":"core_library/jspsych-data/#localsave","text":"Saves a CSV or JSON file on the computer running the experiment. If conducting an online experiment, this will download the file onto the subject's computer, and is therefore not a recommended data storage solution for online data collection. Warning: This function may not behave correctly in older browsers. Upgrading to the latest version of any major web browser should solve the problem. // first argument is the format, second is the filename. // the format can be either 'csv' or 'json'. jsPsych . data . get (). localSave ( 'csv' , 'mydata.csv' );","title":".localSave()"},{"location":"core_library/jspsych-data/#push","text":"Add a new entry to the DataCollection. This method is mostly used internally, and you shouldn't need to call it under normal circumstances. var data = { correct : true , rt : 500 } jsPsych . data . get (). push ( data );","title":".push()"},{"location":"core_library/jspsych-data/#readonly","text":"Creates a copy of the DataCollection so that any modification of the values in the DataCollection will not affect the original. // this line edits the rt property of the first trial jsPsych . data . get (). first ( 1 ). values ()[ 0 ]. rt = 100 ; // readOnly creates a copy that can be modified without affecting the original jsPsych . data . get (). first ( 1 ). values ()[ 0 ]. rt // outputs 100 jsPsych . data . get (). readOnly (). first ( 1 ). values ()[ 0 ]. rt = 200 jsPsych . data . get (). first ( 1 ). values ()[ 0 ]. rt // still outputs 100","title":".readOnly()"},{"location":"core_library/jspsych-data/#select","text":"Returns a DataColumn object (see documentation below) of a single property from a DataCollection object. var rt_data = jsPsych . data . get (). select ( 'rt' ); rt_data . mean ()","title":".select()"},{"location":"core_library/jspsych-data/#uniquenames","text":"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. console . log ( jsPsych . data . get (). uniqueNames ());","title":".uniqueNames()"},{"location":"core_library/jspsych-data/#values","text":"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. var raw_data = jsPsych . data . get (). values (); // was response in first trial correct? if ( raw_data [ 0 ]. correct ){ console . log ( 'correct!' ); } else { console . log ( 'incorrect.' ); }","title":".values()"},{"location":"core_library/jspsych-data/#datacolumn","text":"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.","title":"DataColumn"},{"location":"core_library/jspsych-data/#all","text":"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. // 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 ; });","title":".all()"},{"location":"core_library/jspsych-data/#count_1","text":"Counts the number of values in the DataColumn. // count how many response times there are jsPsych . data . get (). select ( 'rt' ). count ();","title":".count()"},{"location":"core_library/jspsych-data/#frequencies","text":"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. // get frequencies of correct and incorrect responses jsPsych . data . get (). select ( 'correct' ). frequencies ();","title":".frequencies()"},{"location":"core_library/jspsych-data/#max-min","text":"Returns the maximum or minimum value in a DataColumn. jsPsych . data . get (). select ( 'rt' ). max (); jsPsych . data . get (). select ( 'rt' ). min ();","title":".max() / .min()"},{"location":"core_library/jspsych-data/#mean","text":"Returns the average of all the values in a DataColumn. jsPsych . data . get (). select ( 'rt' ). mean ();","title":".mean()"},{"location":"core_library/jspsych-data/#median","text":"Returns the median of all the values in a DataColumn. jsPsych . data . get (). select ( 'rt' ). median ();","title":".median()"},{"location":"core_library/jspsych-data/#sd","text":"Returns the standard deviation of the values in a DataColumn. jsPsych . data . get (). select ( 'rt' ). sd ();","title":".sd()"},{"location":"core_library/jspsych-data/#subset","text":"Filters the DataColumn to include only values that return true when passed through the specified function. // below results will be less than 200. jsPsych . data . get (). select ( 'rt' ). subset ( function ( x ){ return x < 200 ; }). max ();","title":".subset()"},{"location":"core_library/jspsych-data/#sum","text":"Returns the sum of the values in a DataColumn. jsPsych . data . get (). select ( 'rt' ). sum ();","title":".sum()"},{"location":"core_library/jspsych-data/#values_1","text":"The raw array of values in the DataColumn. // note that this is not a function call. jsPsych . data . get (). select ( 'rt' ). values ;","title":".values"},{"location":"core_library/jspsych-data/#variance","text":"Returns the variance of the values in a DataColumn. jsPsych . data . get (). select ( 'rt' ). variance ();","title":".variance()"},{"location":"core_library/jspsych-pluginAPI/","text":"jsPsych.pluginAPI \u00b6 The pluginAPI module contains functions that are useful when developing new plugins. jsPsych.pluginAPI.cancelAllKeyboardResponses \u00b6 jsPsych . pluginAPI . cancelAllKeyboardResponses () Parameters \u00b6 None. Return value \u00b6 Returns nothing. Description \u00b6 Cancels all currently active keyboard listeners created by jsPsych.pluginAPI.getKeyboardResponse . Example \u00b6 jsPsych . pluginAPI . cancelAllKeyboardResponses (); jsPsych.pluginAPI.cancelKeyboardResponse \u00b6 jsPsych . pluginAPI . cancelKeyboardResponse ( listener_id ) Parameters \u00b6 Parameter Type Description listener_id object The listener_id object generated by the call to jsPsych.pluginAPI.getKeyboardResponse . Return value \u00b6 Returns nothing. Description \u00b6 Cancels a specific keyboard listener created by jsPsych.pluginAPI.getKeyboardResponse . Example \u00b6 // create a persistent keyboard listener var listener_id = jsPsych . pluginAPI . getKeyboardResponse ({ callback_function : after_response , valid_responses : [ 'p' , 'q' ], rt_method : 'performance' , persist : true , allow_held_key : false }); // cancel keyboard listener jsPsych . pluginAPI . cancelKeyboardResponse ( listener_id ); jsPsych.pluginAPI.clearAllTimeouts \u00b6 jsPsych . pluginAPI . clearAllTimeouts () Parameters \u00b6 None. Return value \u00b6 Returns nothing. Description \u00b6 Clears any pending timeouts that were set using jsPsych.pluginAPI.setTimeout(). jsPsych.pluginAPI.compareKeys \u00b6 jsPsych . pluginAPI . compareKeys ( key1 , key2 ) Parameters \u00b6 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 \u00b6 Returns true if keycodes or strings refer to the same key, regardless of type. Returns false if the keycodes or strings do not match. Description \u00b6 Compares two keys to see if they are the same, ignoring differences in representational type, and using the appropriate case sensitivity based on the experiment's settings. If case_sensitive_responses is set to false in jsPsych.init (the default), then the string key comparison will not be case-sensitive, e.g., \"a\" and \"A\" will match, and this function will return true . If case_sensitive_responses is set to true in jsPsych.init , then the string key comparison will not be case-sensitive, e.g., \"a\" and \"A\" will not match, and this function will return false . We recommend using this function to compare keys in all plugin and experiment code, rather than using something like if (response == 'j')... . This is because the response key returned by the jsPsych.pluginAPI.getKeyboardResponse function will be converted to lowercase when case_sensitive_responses is false , and it will match the exact key press representation when case_sensitive_responses is true . Using this compareKeys function will ensure that your key comparisons work appropriately based on the experiment's case_sensitive_responses setting, and that you do not need to remember to check key responses against different case versions of the comparison key (e.g. if (response == 'ArrowLeft' || response == 'arrowleft')... ). Examples \u00b6 Basic examples \u00b6 jsPsych . pluginAPI . compareKeys ( 'a' , 'A' ); // returns true when case_sensitive_responses is false in jsPsych.init jsPsych . pluginAPI . compareKeys ( 'a' , 'A' ); // returns false when case_sensitive_responses is true in jsPsych.init // also works with numeric key codes (but note that numeric keyCode values are now deprecated) jsPsych . pluginAPI . compareKeys ( 'a' , 65 ); // returns true jsPsych . pluginAPI . compareKeys ( 'space' , 31 ); // returns false Comparing a key response and key parameter value in plugins \u00b6 // this is the callback_function passed to jsPsych.pluginAPI.getKeyboardResponse var after_response = function ( info ) { // score the response by comparing the key that was pressed against the trial's key_answer parameter var correct = jsPsych . pluginAPI . compareKeys ( trial . key_answer , info . key ); //... } Scoring a key response in experiment code \u00b6 var trial = { type : 'html-keyboard-response' , stimulus : '<<<<<' , choices : [ 'f' , 'j' ], prompt : 'Press f for left. Press j for right.' , on_finish : function ( data ){ // score the response by comparing the key that was pressed (data.response) against the // correct response for this trial ('f'), and store reponse accuracy in the trial data if ( jsPsych . pluginAPI . compareKeys ( data . response , 'f' )){ data . correct = true ; } else { data . correct = false ; } } } jsPsych.pluginAPI.getAudioBuffer \u00b6 jsPsych . pluginAPI . getAudioBuffer ( filepath ) Parameters \u00b6 Parameter Type Description filepath string The path to the audio file that was preloaded. Return value \u00b6 Returns a Promise that resolves when the audio file loads. Success handler's parameter will be the audio buffer. If the experiment is running using the WebAudio API it will be an AudioBuffer object. Otherwise, it will be an HTML5 Audio object. The failure handler's parameter is the error generated by preloadAudio . Description \u00b6 Gets an AudioBuffer that can be played with the WebAudio API or an Audio object that can be played with HTML5 Audio. It is strongly recommended that you preload audio files before calling this method. This method will load the files if they are not preloaded, but this may result in delays during the experiment as audio is downloaded. Examples \u00b6 HTML 5 Audio \u00b6 jsPsych . pluginAPI . getAudioBuffer ( 'my-sound.mp3' ) . then ( function ( audio ){ audio . play (); }) . catch ( function ( err ){ console . error ( 'Audio file failed to load' ) }) WebAudio API \u00b6 var context = jsPsych . pluginAPI . audioContext (); jsPsych . pluginAPI . getAudioBuffer ( 'my-sound.mp3' ) . then ( function ( buffer ){ audio = context . createBufferSource (); audio . buffer = buffer ; audio . connect ( context . destination ); audio . start ( context . currentTime ); }) . catch ( function ( err ){ console . error ( 'Audio file failed to load' ) }) See the audio-keyboard-response plugin for an example in a fuller context. jsPsych.pluginAPI.getAutoPreloadList \u00b6 jsPsych . pluginAPI . getAutoPreloadList ( timeline ) Parameters \u00b6 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 \u00b6 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 \u00b6 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 for more information. Example \u00b6 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 \u00b6 jsPsych . pluginAPI . getKeyboardResponse ( parameters ) Parameters \u00b6 The method accepts an object of parameter values (see example below). The valid keys for this object are listed in the table below. Parameter Type Description callback_function function The function to execute whenever a valid keyboard response is generated. valid_responses array An array of key codes or character strings representing valid responses. Responses not on the list will be ignored. An empty array indicates that all responses are acceptable. rt_method string Indicates which method of recording time to use. The 'performance' method uses calls to performance.now() , which is the standard way of measuring timing in jsPsych. It is supported by up-to-date versions of all the major browsers . The audio method is used in conjuction with an audio_context (set as an additional parameter). This uses the clock time of the audio_context when audio stimuli are being played. audio_context AudioContext object The AudioContext of the audio file that is being played. audio_context_start_time numeric The scheduled time of the sound file in the AudioContext. This will be used as the start time. allow_held_key boolean If true , then responses will be registered from keys that are being held down. If false , then a held key can only register a response the first time that getKeyboardResponse is called for that key. For example, if a participant holds down the A key before the experiment starts, then the first time getKeyboardResponse is called, the A will register as a key press. However, any future calls to getKeyboardResponse will not register the A until the participant releases the key and presses it again. persist boolean If false, then the keyboard listener will only trigger the first time a valid key is pressed. If true, then it will trigger every time a valid key is pressed until it is explicitly cancelled by jsPsych.pluginAPI.cancelKeyboardResponse or jsPsych.pluginAPI.cancelAllKeyboardResponses . Return value \u00b6 Return an object that uniquely identifies the keyboard listener. This object can be passed to jsPsych.pluginAPI.cancelKeyboardResponse to cancel the keyboard listener. Description \u00b6 Gets a keyboard response from the subject, recording the response time from when the function is first called until a valid response is generated. The keyboard event listener will be bound to the display_element declared in jsPsych.init() (or the element if no display_element is specified). This allows jsPsych experiments to be embedded in websites with other content without disrupting the functionality of other UI elements. A valid response triggers the callback_function specified in the parameters. A single argument is passed to the callback function. The argument contains an object with the properties key and rt . key contains the string representation of the response key, and rt contains the response time. This function uses the .key value of the keyboard event, which is case sensitive . When case_sensitive_responses is false in jsPsych.init (the default), this function will convert both the valid_responses strings and the response key to lowercase before comparing them, and it will pass the lowercase version of the response key to the callback_function . For example, if valid_responses is ['a'] , then both 'A' and 'a' will be considered valid key presses, and 'a' will be returned as the response key. When case_sensitive_responses is true in jsPsych.init , this function will not convert the case when comparing the valid_responses and response key, and it will not convert the case of the response key that is passed to the callback_function . For example, if valid_responses is ['a'] , then 'a' will be the only valid key press, and 'A' (i.e. 'a' with CapsLock on or Shift held down) will not be accepted. Also, if valid_responses includes multiple letter case options (e.g. jsPsych.ALL_KEYS ), then you may need to check the response key against both letter cases when scoring etc., e.g. if (response == 'ArrowLeft' || response =='arrowleft') ... . Examples \u00b6 Get a single response from any key \u00b6 var after_response = function ( info ){ alert ( 'You pressed key ' + info . key + ' after ' + info . rt + 'ms' ); } jsPsych . pluginAPI . getKeyboardResponse ({ callback_function : after_response , valid_responses : jsPsych . ALL_KEYS , rt_method : 'performance' , persist : false }); Get a responses from a key until the letter q is pressed \u00b6 var after_response = function ( info ){ alert ( 'You pressed key ' + info . key + ' after ' + info . rt + 'ms' ); if ( jsPsych . pluginAPI . compareKeys ( info . key , 'q' )){ / jsPsych . pluginAPI . cancelKeyboardResponse ( listener ); } } var listener = jsPsych . pluginAPI . getKeyboardResponse ({ callback_function : after_response , valid_responses : jsPsych . ALL_KEYS , rt_method : 'performance' , persist : true }); jsPsych.pluginAPI.preloadAudio \u00b6 jsPsych . pluginAPI . preloadAudio ( files , callback_complete , callback_load , callback_error ) Parameters \u00b6 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 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 \u00b6 Returns nothing. Description \u00b6 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 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 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 \u00b6 Basic use \u00b6 var sounds = [ 'file1.mp3' , 'file2.mp3' , 'file3.mp3' ]; 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 ({ timeline : exp }); } Show progress of loading \u00b6 var sounds = [ 'file1.mp3' , 'file2.mp3' , 'file3.mp3' ]; var n_loaded = 0 ; jsPsych . pluginAPI . preloadAudio ( sounds , function (){ startExperiment (); }, function ( file ) { updateLoadedCount ( file ); }); 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. console . log ( 'Loaded ' + percentcomplete + '% of audio files' ); } function startExperiment (){ jsPsych . init ({ timeline : exp }); } jsPsych.pluginAPI.preloadImages \u00b6 jsPsych . pluginAPI . preloadImages ( images , callback_complete , callback_load , callback_error ) Parameters \u00b6 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 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 \u00b6 Returns nothing. Description \u00b6 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 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 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 \u00b6 Basic use \u00b6 var images = [ 'img/file1.png' , 'img/file2.png' , 'img/file3.png' ]; 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 ({ timeline : exp }); } Show progress of loading \u00b6 var images = [ 'img/file1.png' , 'img/file2.png' , 'img/file3.png' ]; var n_loaded = 0 ; jsPsych . pluginAPI . preloadImages ( images , function (){ startExperiment (); }, function ( file ) { updateLoadedCount ( file ); }); 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. console . log ( 'Loaded ' + percentcomplete + '% of images' ); } function startExperiment (){ jsPsych . init ({ timeline : exp }); } jsPsych.pluginAPI.preloadVideo \u00b6 jsPsych . pluginAPI . preloadVideo ( video , callback_complete , callback_load , callback_error ) Parameters \u00b6 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 \u00b6 Returns nothing. Description \u00b6 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 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 \u00b6 Basic use \u00b6 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 \u00b6 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 \u00b6 jsPsych . pluginAPI . registerPreload ( plugin_name , parameter , media_type ) Parameters \u00b6 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', 'audio' or 'video'. Return value \u00b6 Nothing. Description \u00b6 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. Example \u00b6 For an example, see the image-keyboard-response and audio-keyboard-response plugins. jsPsych.pluginAPI.setTimeout \u00b6 jsPsych . pluginAPI . setTimeout ( callback , delay ) Parameters \u00b6 Parameter Type Description callback function A function to execute after waiting for delay. delay integer Time to wait in milliseconds. Return value \u00b6 Returns the ID of the setTimeout handle. Description \u00b6 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. Example \u00b6 // print the time console . log ( Date . now ()) // print the time 1s later jsPsych . pluginAPI . setTimeout ( function (){ console . log ( Date . now ()) }, 1000 );","title":"jsPsych.pluginAPI"},{"location":"core_library/jspsych-pluginAPI/#jspsychpluginapi","text":"The pluginAPI module contains functions that are useful when developing new plugins.","title":"jsPsych.pluginAPI"},{"location":"core_library/jspsych-pluginAPI/#jspsychpluginapicancelallkeyboardresponses","text":"jsPsych . pluginAPI . cancelAllKeyboardResponses ()","title":"jsPsych.pluginAPI.cancelAllKeyboardResponses"},{"location":"core_library/jspsych-pluginAPI/#parameters","text":"None.","title":"Parameters"},{"location":"core_library/jspsych-pluginAPI/#return-value","text":"Returns nothing.","title":"Return value"},{"location":"core_library/jspsych-pluginAPI/#description","text":"Cancels all currently active keyboard listeners created by jsPsych.pluginAPI.getKeyboardResponse .","title":"Description"},{"location":"core_library/jspsych-pluginAPI/#example","text":"jsPsych . pluginAPI . cancelAllKeyboardResponses ();","title":"Example"},{"location":"core_library/jspsych-pluginAPI/#jspsychpluginapicancelkeyboardresponse","text":"jsPsych . pluginAPI . cancelKeyboardResponse ( listener_id )","title":"jsPsych.pluginAPI.cancelKeyboardResponse"},{"location":"core_library/jspsych-pluginAPI/#parameters_1","text":"Parameter Type Description listener_id object The listener_id object generated by the call to jsPsych.pluginAPI.getKeyboardResponse .","title":"Parameters"},{"location":"core_library/jspsych-pluginAPI/#return-value_1","text":"Returns nothing.","title":"Return value"},{"location":"core_library/jspsych-pluginAPI/#description_1","text":"Cancels a specific keyboard listener created by jsPsych.pluginAPI.getKeyboardResponse .","title":"Description"},{"location":"core_library/jspsych-pluginAPI/#example_1","text":"// create a persistent keyboard listener var listener_id = jsPsych . pluginAPI . getKeyboardResponse ({ callback_function : after_response , valid_responses : [ 'p' , 'q' ], rt_method : 'performance' , persist : true , allow_held_key : false }); // cancel keyboard listener jsPsych . pluginAPI . cancelKeyboardResponse ( listener_id );","title":"Example"},{"location":"core_library/jspsych-pluginAPI/#jspsychpluginapiclearalltimeouts","text":"jsPsych . pluginAPI . clearAllTimeouts ()","title":"jsPsych.pluginAPI.clearAllTimeouts"},{"location":"core_library/jspsych-pluginAPI/#parameters_2","text":"None.","title":"Parameters"},{"location":"core_library/jspsych-pluginAPI/#return-value_2","text":"Returns nothing.","title":"Return value"},{"location":"core_library/jspsych-pluginAPI/#description_2","text":"Clears any pending timeouts that were set using jsPsych.pluginAPI.setTimeout().","title":"Description"},{"location":"core_library/jspsych-pluginAPI/#jspsychpluginapicomparekeys","text":"jsPsych . pluginAPI . compareKeys ( key1 , key2 )","title":"jsPsych.pluginAPI.compareKeys"},{"location":"core_library/jspsych-pluginAPI/#parameters_3","text":"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","title":"Parameters"},{"location":"core_library/jspsych-pluginAPI/#return-value_3","text":"Returns true if keycodes or strings refer to the same key, regardless of type. Returns false if the keycodes or strings do not match.","title":"Return value"},{"location":"core_library/jspsych-pluginAPI/#description_3","text":"Compares two keys to see if they are the same, ignoring differences in representational type, and using the appropriate case sensitivity based on the experiment's settings. If case_sensitive_responses is set to false in jsPsych.init (the default), then the string key comparison will not be case-sensitive, e.g., \"a\" and \"A\" will match, and this function will return true . If case_sensitive_responses is set to true in jsPsych.init , then the string key comparison will not be case-sensitive, e.g., \"a\" and \"A\" will not match, and this function will return false . We recommend using this function to compare keys in all plugin and experiment code, rather than using something like if (response == 'j')... . This is because the response key returned by the jsPsych.pluginAPI.getKeyboardResponse function will be converted to lowercase when case_sensitive_responses is false , and it will match the exact key press representation when case_sensitive_responses is true . Using this compareKeys function will ensure that your key comparisons work appropriately based on the experiment's case_sensitive_responses setting, and that you do not need to remember to check key responses against different case versions of the comparison key (e.g. if (response == 'ArrowLeft' || response == 'arrowleft')... ).","title":"Description"},{"location":"core_library/jspsych-pluginAPI/#examples","text":"","title":"Examples"},{"location":"core_library/jspsych-pluginAPI/#basic-examples","text":"jsPsych . pluginAPI . compareKeys ( 'a' , 'A' ); // returns true when case_sensitive_responses is false in jsPsych.init jsPsych . pluginAPI . compareKeys ( 'a' , 'A' ); // returns false when case_sensitive_responses is true in jsPsych.init // also works with numeric key codes (but note that numeric keyCode values are now deprecated) jsPsych . pluginAPI . compareKeys ( 'a' , 65 ); // returns true jsPsych . pluginAPI . compareKeys ( 'space' , 31 ); // returns false","title":"Basic examples"},{"location":"core_library/jspsych-pluginAPI/#comparing-a-key-response-and-key-parameter-value-in-plugins","text":"// this is the callback_function passed to jsPsych.pluginAPI.getKeyboardResponse var after_response = function ( info ) { // score the response by comparing the key that was pressed against the trial's key_answer parameter var correct = jsPsych . pluginAPI . compareKeys ( trial . key_answer , info . key ); //... }","title":"Comparing a key response and key parameter value in plugins"},{"location":"core_library/jspsych-pluginAPI/#scoring-a-key-response-in-experiment-code","text":"var trial = { type : 'html-keyboard-response' , stimulus : '<<<<<' , choices : [ 'f' , 'j' ], prompt : 'Press f for left. Press j for right.' , on_finish : function ( data ){ // score the response by comparing the key that was pressed (data.response) against the // correct response for this trial ('f'), and store reponse accuracy in the trial data if ( jsPsych . pluginAPI . compareKeys ( data . response , 'f' )){ data . correct = true ; } else { data . correct = false ; } } }","title":"Scoring a key response in experiment code"},{"location":"core_library/jspsych-pluginAPI/#jspsychpluginapigetaudiobuffer","text":"jsPsych . pluginAPI . getAudioBuffer ( filepath )","title":"jsPsych.pluginAPI.getAudioBuffer"},{"location":"core_library/jspsych-pluginAPI/#parameters_4","text":"Parameter Type Description filepath string The path to the audio file that was preloaded.","title":"Parameters"},{"location":"core_library/jspsych-pluginAPI/#return-value_4","text":"Returns a Promise that resolves when the audio file loads. Success handler's parameter will be the audio buffer. If the experiment is running using the WebAudio API it will be an AudioBuffer object. Otherwise, it will be an HTML5 Audio object. The failure handler's parameter is the error generated by preloadAudio .","title":"Return value"},{"location":"core_library/jspsych-pluginAPI/#description_4","text":"Gets an AudioBuffer that can be played with the WebAudio API or an Audio object that can be played with HTML5 Audio. It is strongly recommended that you preload audio files before calling this method. This method will load the files if they are not preloaded, but this may result in delays during the experiment as audio is downloaded.","title":"Description"},{"location":"core_library/jspsych-pluginAPI/#examples_1","text":"","title":"Examples"},{"location":"core_library/jspsych-pluginAPI/#html-5-audio","text":"jsPsych . pluginAPI . getAudioBuffer ( 'my-sound.mp3' ) . then ( function ( audio ){ audio . play (); }) . catch ( function ( err ){ console . error ( 'Audio file failed to load' ) })","title":"HTML 5 Audio"},{"location":"core_library/jspsych-pluginAPI/#webaudio-api","text":"var context = jsPsych . pluginAPI . audioContext (); jsPsych . pluginAPI . getAudioBuffer ( 'my-sound.mp3' ) . then ( function ( buffer ){ audio = context . createBufferSource (); audio . buffer = buffer ; audio . connect ( context . destination ); audio . start ( context . currentTime ); }) . catch ( function ( err ){ console . error ( 'Audio file failed to load' ) }) See the audio-keyboard-response plugin for an example in a fuller context.","title":"WebAudio API"},{"location":"core_library/jspsych-pluginAPI/#jspsychpluginapigetautopreloadlist","text":"jsPsych . pluginAPI . getAutoPreloadList ( timeline )","title":"jsPsych.pluginAPI.getAutoPreloadList"},{"location":"core_library/jspsych-pluginAPI/#parameters_5","text":"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.","title":"Parameters"},{"location":"core_library/jspsych-pluginAPI/#return-value_5","text":"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.","title":"Return value"},{"location":"core_library/jspsych-pluginAPI/#description_5","text":"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 for more information.","title":"Description"},{"location":"core_library/jspsych-pluginAPI/#example_2","text":"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 );","title":"Example"},{"location":"core_library/jspsych-pluginAPI/#jspsychpluginapigetkeyboardresponse","text":"jsPsych . pluginAPI . getKeyboardResponse ( parameters )","title":"jsPsych.pluginAPI.getKeyboardResponse"},{"location":"core_library/jspsych-pluginAPI/#parameters_6","text":"The method accepts an object of parameter values (see example below). The valid keys for this object are listed in the table below. Parameter Type Description callback_function function The function to execute whenever a valid keyboard response is generated. valid_responses array An array of key codes or character strings representing valid responses. Responses not on the list will be ignored. An empty array indicates that all responses are acceptable. rt_method string Indicates which method of recording time to use. The 'performance' method uses calls to performance.now() , which is the standard way of measuring timing in jsPsych. It is supported by up-to-date versions of all the major browsers . The audio method is used in conjuction with an audio_context (set as an additional parameter). This uses the clock time of the audio_context when audio stimuli are being played. audio_context AudioContext object The AudioContext of the audio file that is being played. audio_context_start_time numeric The scheduled time of the sound file in the AudioContext. This will be used as the start time. allow_held_key boolean If true , then responses will be registered from keys that are being held down. If false , then a held key can only register a response the first time that getKeyboardResponse is called for that key. For example, if a participant holds down the A key before the experiment starts, then the first time getKeyboardResponse is called, the A will register as a key press. However, any future calls to getKeyboardResponse will not register the A until the participant releases the key and presses it again. persist boolean If false, then the keyboard listener will only trigger the first time a valid key is pressed. If true, then it will trigger every time a valid key is pressed until it is explicitly cancelled by jsPsych.pluginAPI.cancelKeyboardResponse or jsPsych.pluginAPI.cancelAllKeyboardResponses .","title":"Parameters"},{"location":"core_library/jspsych-pluginAPI/#return-value_6","text":"Return an object that uniquely identifies the keyboard listener. This object can be passed to jsPsych.pluginAPI.cancelKeyboardResponse to cancel the keyboard listener.","title":"Return value"},{"location":"core_library/jspsych-pluginAPI/#description_6","text":"Gets a keyboard response from the subject, recording the response time from when the function is first called until a valid response is generated. The keyboard event listener will be bound to the display_element declared in jsPsych.init() (or the element if no display_element is specified). This allows jsPsych experiments to be embedded in websites with other content without disrupting the functionality of other UI elements. A valid response triggers the callback_function specified in the parameters. A single argument is passed to the callback function. The argument contains an object with the properties key and rt . key contains the string representation of the response key, and rt contains the response time. This function uses the .key value of the keyboard event, which is case sensitive . When case_sensitive_responses is false in jsPsych.init (the default), this function will convert both the valid_responses strings and the response key to lowercase before comparing them, and it will pass the lowercase version of the response key to the callback_function . For example, if valid_responses is ['a'] , then both 'A' and 'a' will be considered valid key presses, and 'a' will be returned as the response key. When case_sensitive_responses is true in jsPsych.init , this function will not convert the case when comparing the valid_responses and response key, and it will not convert the case of the response key that is passed to the callback_function . For example, if valid_responses is ['a'] , then 'a' will be the only valid key press, and 'A' (i.e. 'a' with CapsLock on or Shift held down) will not be accepted. Also, if valid_responses includes multiple letter case options (e.g. jsPsych.ALL_KEYS ), then you may need to check the response key against both letter cases when scoring etc., e.g. if (response == 'ArrowLeft' || response =='arrowleft') ... .","title":"Description"},{"location":"core_library/jspsych-pluginAPI/#examples_2","text":"","title":"Examples"},{"location":"core_library/jspsych-pluginAPI/#get-a-single-response-from-any-key","text":"var after_response = function ( info ){ alert ( 'You pressed key ' + info . key + ' after ' + info . rt + 'ms' ); } jsPsych . pluginAPI . getKeyboardResponse ({ callback_function : after_response , valid_responses : jsPsych . ALL_KEYS , rt_method : 'performance' , persist : false });","title":"Get a single response from any key"},{"location":"core_library/jspsych-pluginAPI/#get-a-responses-from-a-key-until-the-letter-q-is-pressed","text":"var after_response = function ( info ){ alert ( 'You pressed key ' + info . key + ' after ' + info . rt + 'ms' ); if ( jsPsych . pluginAPI . compareKeys ( info . key , 'q' )){ / jsPsych . pluginAPI . cancelKeyboardResponse ( listener ); } } var listener = jsPsych . pluginAPI . getKeyboardResponse ({ callback_function : after_response , valid_responses : jsPsych . ALL_KEYS , rt_method : 'performance' , persist : true });","title":"Get a responses from a key until the letter q is pressed"},{"location":"core_library/jspsych-pluginAPI/#jspsychpluginapipreloadaudio","text":"jsPsych . pluginAPI . preloadAudio ( files , callback_complete , callback_load , callback_error )","title":"jsPsych.pluginAPI.preloadAudio"},{"location":"core_library/jspsych-pluginAPI/#parameters_7","text":"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 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.","title":"Parameters"},{"location":"core_library/jspsych-pluginAPI/#return-value_7","text":"Returns nothing.","title":"Return value"},{"location":"core_library/jspsych-pluginAPI/#description_7","text":"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 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 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.","title":"Description"},{"location":"core_library/jspsych-pluginAPI/#examples_3","text":"","title":"Examples"},{"location":"core_library/jspsych-pluginAPI/#basic-use","text":"var sounds = [ 'file1.mp3' , 'file2.mp3' , 'file3.mp3' ]; 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 ({ timeline : exp }); }","title":"Basic use"},{"location":"core_library/jspsych-pluginAPI/#show-progress-of-loading","text":"var sounds = [ 'file1.mp3' , 'file2.mp3' , 'file3.mp3' ]; var n_loaded = 0 ; jsPsych . pluginAPI . preloadAudio ( sounds , function (){ startExperiment (); }, function ( file ) { updateLoadedCount ( file ); }); 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. console . log ( 'Loaded ' + percentcomplete + '% of audio files' ); } function startExperiment (){ jsPsych . init ({ timeline : exp }); }","title":"Show progress of loading"},{"location":"core_library/jspsych-pluginAPI/#jspsychpluginapipreloadimages","text":"jsPsych . pluginAPI . preloadImages ( images , callback_complete , callback_load , callback_error )","title":"jsPsych.pluginAPI.preloadImages"},{"location":"core_library/jspsych-pluginAPI/#parameters_8","text":"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 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.","title":"Parameters"},{"location":"core_library/jspsych-pluginAPI/#return-value_8","text":"Returns nothing.","title":"Return value"},{"location":"core_library/jspsych-pluginAPI/#description_8","text":"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 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 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.","title":"Description"},{"location":"core_library/jspsych-pluginAPI/#examples_4","text":"","title":"Examples"},{"location":"core_library/jspsych-pluginAPI/#basic-use_1","text":"var images = [ 'img/file1.png' , 'img/file2.png' , 'img/file3.png' ]; 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 ({ timeline : exp }); }","title":"Basic use"},{"location":"core_library/jspsych-pluginAPI/#show-progress-of-loading_1","text":"var images = [ 'img/file1.png' , 'img/file2.png' , 'img/file3.png' ]; var n_loaded = 0 ; jsPsych . pluginAPI . preloadImages ( images , function (){ startExperiment (); }, function ( file ) { updateLoadedCount ( file ); }); 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. console . log ( 'Loaded ' + percentcomplete + '% of images' ); } function startExperiment (){ jsPsych . init ({ timeline : exp }); }","title":"Show progress of loading"},{"location":"core_library/jspsych-pluginAPI/#jspsychpluginapipreloadvideo","text":"jsPsych . pluginAPI . preloadVideo ( video , callback_complete , callback_load , callback_error )","title":"jsPsych.pluginAPI.preloadVideo"},{"location":"core_library/jspsych-pluginAPI/#parameters_9","text":"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.","title":"Parameters"},{"location":"core_library/jspsych-pluginAPI/#return-value_9","text":"Returns nothing.","title":"Return value"},{"location":"core_library/jspsych-pluginAPI/#description_9","text":"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 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.","title":"Description"},{"location":"core_library/jspsych-pluginAPI/#examples_5","text":"","title":"Examples"},{"location":"core_library/jspsych-pluginAPI/#basic-use_2","text":"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 }); }","title":"Basic use"},{"location":"core_library/jspsych-pluginAPI/#show-progress-of-loading_2","text":"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 }); }","title":"Show progress of loading"},{"location":"core_library/jspsych-pluginAPI/#jspsychpluginapiregisterpreload","text":"jsPsych . pluginAPI . registerPreload ( plugin_name , parameter , media_type )","title":"jsPsych.pluginAPI.registerPreload"},{"location":"core_library/jspsych-pluginAPI/#parameters_10","text":"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', 'audio' or 'video'.","title":"Parameters"},{"location":"core_library/jspsych-pluginAPI/#return-value_10","text":"Nothing.","title":"Return value"},{"location":"core_library/jspsych-pluginAPI/#description_10","text":"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.","title":"Description"},{"location":"core_library/jspsych-pluginAPI/#example_3","text":"For an example, see the image-keyboard-response and audio-keyboard-response plugins.","title":"Example"},{"location":"core_library/jspsych-pluginAPI/#jspsychpluginapisettimeout","text":"jsPsych . pluginAPI . setTimeout ( callback , delay )","title":"jsPsych.pluginAPI.setTimeout"},{"location":"core_library/jspsych-pluginAPI/#parameters_11","text":"Parameter Type Description callback function A function to execute after waiting for delay. delay integer Time to wait in milliseconds.","title":"Parameters"},{"location":"core_library/jspsych-pluginAPI/#return-value_11","text":"Returns the ID of the setTimeout handle.","title":"Return value"},{"location":"core_library/jspsych-pluginAPI/#description_11","text":"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.","title":"Description"},{"location":"core_library/jspsych-pluginAPI/#example_4","text":"// print the time console . log ( Date . now ()) // print the time 1s later jsPsych . pluginAPI . setTimeout ( function (){ console . log ( Date . now ()) }, 1000 );","title":"Example"},{"location":"core_library/jspsych-randomization/","text":"jsPsych.randomization \u00b6 The jsPsych.randomization module contains methods that are useful for generating random lists of trial variables. jsPsych.randomization.factorial \u00b6 jsPsych . randomization . factorial ( factors , repetitions , unpack ) Parameters \u00b6 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 \u00b6 The return value depends on the unpack parameter. See description of the parameter above, and examples below. Description \u00b6 This method takes a list of factors and their levels, and creates a full factorial design by creating each unique combination of the factors. The returned set of combinations is in a random order. Examples \u00b6 Create full factorial design \u00b6 var factors = { stimulus : [ 'a.jpg' , 'b.jpg' ], ms_delay : [ 100 , 200 ] } var full_design = jsPsych . randomization . factorial ( factors , 1 ); /* output: full_design = [ {stimulus: 'a.jpg', ms_delay: 200}, {stimulus: 'b.jpg', ms_delay: 200}, {stimulus: 'b.jpg', ms_delay: 100}, {stimulus: 'a.jpg', ms_delay: 100}, ] */ Create full factorial design with repeats \u00b6 var factors = { stimulus : [ 'a.jpg' , 'b.jpg' ], ms_delay : [ 100 , 200 ] } var full_design = jsPsych . randomization . factorial ( factors , 2 ); /* output: full_design = [ {stimulus: 'b.jpg', ms_delay: 200}, {stimulus: 'b.jpg', ms_delay: 100}, {stimulus: 'b.jpg', ms_delay: 100}, {stimulus: 'a.jpg', ms_delay: 100}, {stimulus: 'a.jpg', ms_delay: 200}, {stimulus: 'b.jpg', ms_delay: 200}, {stimulus: 'a.jpg', ms_delay: 100}, {stimulus: 'a.jpg', ms_delay: 200}, ] */ Create full factorial design, unpacked \u00b6 var factors = { stimulus : [ 'a.jpg' , 'b.jpg' ], ms_delay : [ 100 , 200 ] } var full_design = jsPsych . randomization . factorial ( factors , 1 , true ); /* output: full_design = { stimulus: ['a.jpg','b.jpg','b.jpg','a.jpg'], ms_delay: [200, 100, 200, 100] ] */ jsPsych.randomization.randomID \u00b6 jsPsych . randomization . randomID ( length ) Parameters \u00b6 Parameter Type Description length integer The length of the randomly generated ID Return value \u00b6 Returns a string of length length where each character is randomly selected from the numbers 0-9 and all lowercase English letters a-z. Description \u00b6 Generates a random string that is likely to be unique. If length is undefined, then the string length is 32. Example \u00b6 console . log ( jsPsych . randomization . randomID ()); // outputs: \"t7dwz0e713pc8juuaayyfvpkdd9un239\" console . log ( jsPsych . randomization . randomID ( 8 )); // outputs: \"3xtpcbck\" jsPsych.randomization.repeat \u00b6 jsPsych . randomization . repeat ( array , repetitions , unpack ) Parameters \u00b6 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 \u00b6 The return value depends on the unpack parameter. See description of the parameter above, and examples below. Description \u00b6 This method takes an array of values and generates a new random order of the array, with the option of repeating each element of the array a specified number of times. If the array elements are objects with the same set of properties, then this method can optionally return a single object where each property is a randomized order of the properties defined in the original set of objects. This is useful for randomizing sets of parameters that are used to define a jsPsych block. Examples \u00b6 Shuffle an array, no repeats \u00b6 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 \u00b6 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 \u00b6 var trial1 = { stimulus : 'img/faceA.jpg' , correct_key : 'p' , person_name : 'Joe' } var trial2 = { stimulus : 'img/faceB.jpg' , correct_key : 'p' , person_name : 'Fred' } var trial3 = { stimulus : 'img/faceC.jpg' , correct_key : 'q' , person_name : 'Mary' } var myArray = [ trial1 , trial2 , trial3 ]; var shuffledArray = jsPsych . randomization . repeat ( myArray , 2 ); // output: shuffledArray = [ trial1, trial3, trial3, trial2, trial1, trial2 ] Shuffle an array of objects, with unpack \u00b6 var trial1 = { stimulus : 'img/faceA.jpg' , correct_key : 'p' , person_name : 'Joe' } var trial2 = { stimulus : 'img/faceB.jpg' , correct_key : 'p' , person_name : 'Fred' } var trial3 = { stimulus : 'img/faceC.jpg' , correct_key : 'q' , person_name : 'Mary' } var myArray = [ trial1 , trial2 , trial3 ]; 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: ['p', 'p', 'q', 'p', 'q', 'p'], person_name: ['Fred', 'Joe', 'Mary', 'Joe', 'Mary', 'Fred'] } */ jsPsych.randomization.sampleWithReplacement \u00b6 jsPsych . randomization . sampleWithReplacement ( array , sampleSize , weights ) Parameters \u00b6 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 \u00b6 An array containing the sample. Description \u00b6 This method returns a sample drawn at random from a set of values with replacement. The relative probability of drawing each item can be controlled by specifying the weights . Examples \u00b6 Sample with equal probability \u00b6 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 \u00b6 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 \u00b6 jsPsych . randomization . sampleWithoutReplacement ( array , sampleSize ) Parameters \u00b6 Parameter Type Description array array The array of values to sample from sampleSize numeric The number of samples to draw Return value \u00b6 An array containing the sample. Description \u00b6 This method returns a sample drawn at random from a set of values without replacement. The sample size must be less than or equal to the length of the array. Examples \u00b6 Sample without replacement \u00b6 var myArray = [ 1 , 2 , 3 , 4 , 5 ]; var sample = jsPsych . randomization . sampleWithoutReplacement ( myArray , 2 ); // output: sample = [3,2]; jsPsych.randomization.shuffle \u00b6 jsPsych . randomization . shuffle ( array ) Parameters \u00b6 Parameter Type Description array array The array of values to shuffle Return value \u00b6 Returns an array with the same elements as the input array in a random order. Description \u00b6 A simple method for shuffling the order of an array. Examples \u00b6 Shuffle an array \u00b6 var myArray = [ 1 , 2 , 3 , 4 , 5 ]; var shuffledArray = jsPsych . randomization . shuffle ( myArray ); // output: shuffledArray = [3,2,4,1,5] jsPsych.randomization.shuffleNoRepeats \u00b6 jsPsych . randomization . shuffleNoRepeats ( array , equalityTest ) Parameters \u00b6 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 \u00b6 Returns an array with the same elements as the input array in a random order, with no repeating neighbors. Description \u00b6 Shuffle an array, ensuring that neighboring elements in the array are different. Warning: if you provide an array that has very few valid permutations with no neighboring elements, then this method will fail and cause the browser to hang. Examples \u00b6 Basic example \u00b6 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] Custom equalityTest \u00b6 var myObjects = [ { color : \"blue\" }, { color : \"red\" }, { color : \"yellow\" }, { color : \"orange\" } ]; var repeatedSet = jsPsych . randomization . repeat ( myObjects , 3 ); var shuffled = jsPsych . randomization . shuffleNoRepeats ( repeatedSet , function ( a , b ) { return a . color === b . color }); // console.log(JSON.stringify(shuffled)) // \"[{\"color\":\"red\"},{\"color\":\"yellow\"},{\"color\":\"blue\"},{\"color\":\"yellow\"},{\"color\":\"orange\"},{\"color\":\"red\"},{\"color\":\"yellow\"},{\"color\":\"orange\"},{\"color\":\"blue\"},{\"color\":\"orange\"},{\"color\":\"red\"},{\"color\":\"blue\"}]\"","title":"jsPsych.randomization"},{"location":"core_library/jspsych-randomization/#jspsychrandomization","text":"The jsPsych.randomization module contains methods that are useful for generating random lists of trial variables.","title":"jsPsych.randomization"},{"location":"core_library/jspsych-randomization/#jspsychrandomizationfactorial","text":"jsPsych . randomization . factorial ( factors , repetitions , unpack )","title":"jsPsych.randomization.factorial"},{"location":"core_library/jspsych-randomization/#parameters","text":"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.","title":"Parameters"},{"location":"core_library/jspsych-randomization/#return-value","text":"The return value depends on the unpack parameter. See description of the parameter above, and examples below.","title":"Return value"},{"location":"core_library/jspsych-randomization/#description","text":"This method takes a list of factors and their levels, and creates a full factorial design by creating each unique combination of the factors. The returned set of combinations is in a random order.","title":"Description"},{"location":"core_library/jspsych-randomization/#examples","text":"","title":"Examples"},{"location":"core_library/jspsych-randomization/#create-full-factorial-design","text":"var factors = { stimulus : [ 'a.jpg' , 'b.jpg' ], ms_delay : [ 100 , 200 ] } var full_design = jsPsych . randomization . factorial ( factors , 1 ); /* output: full_design = [ {stimulus: 'a.jpg', ms_delay: 200}, {stimulus: 'b.jpg', ms_delay: 200}, {stimulus: 'b.jpg', ms_delay: 100}, {stimulus: 'a.jpg', ms_delay: 100}, ] */","title":"Create full factorial design"},{"location":"core_library/jspsych-randomization/#create-full-factorial-design-with-repeats","text":"var factors = { stimulus : [ 'a.jpg' , 'b.jpg' ], ms_delay : [ 100 , 200 ] } var full_design = jsPsych . randomization . factorial ( factors , 2 ); /* output: full_design = [ {stimulus: 'b.jpg', ms_delay: 200}, {stimulus: 'b.jpg', ms_delay: 100}, {stimulus: 'b.jpg', ms_delay: 100}, {stimulus: 'a.jpg', ms_delay: 100}, {stimulus: 'a.jpg', ms_delay: 200}, {stimulus: 'b.jpg', ms_delay: 200}, {stimulus: 'a.jpg', ms_delay: 100}, {stimulus: 'a.jpg', ms_delay: 200}, ] */","title":"Create full factorial design with repeats"},{"location":"core_library/jspsych-randomization/#create-full-factorial-design-unpacked","text":"var factors = { stimulus : [ 'a.jpg' , 'b.jpg' ], ms_delay : [ 100 , 200 ] } var full_design = jsPsych . randomization . factorial ( factors , 1 , true ); /* output: full_design = { stimulus: ['a.jpg','b.jpg','b.jpg','a.jpg'], ms_delay: [200, 100, 200, 100] ] */","title":"Create full factorial design, unpacked"},{"location":"core_library/jspsych-randomization/#jspsychrandomizationrandomid","text":"jsPsych . randomization . randomID ( length )","title":"jsPsych.randomization.randomID"},{"location":"core_library/jspsych-randomization/#parameters_1","text":"Parameter Type Description length integer The length of the randomly generated ID","title":"Parameters"},{"location":"core_library/jspsych-randomization/#return-value_1","text":"Returns a string of length length where each character is randomly selected from the numbers 0-9 and all lowercase English letters a-z.","title":"Return value"},{"location":"core_library/jspsych-randomization/#description_1","text":"Generates a random string that is likely to be unique. If length is undefined, then the string length is 32.","title":"Description"},{"location":"core_library/jspsych-randomization/#example","text":"console . log ( jsPsych . randomization . randomID ()); // outputs: \"t7dwz0e713pc8juuaayyfvpkdd9un239\" console . log ( jsPsych . randomization . randomID ( 8 )); // outputs: \"3xtpcbck\"","title":"Example"},{"location":"core_library/jspsych-randomization/#jspsychrandomizationrepeat","text":"jsPsych . randomization . repeat ( array , repetitions , unpack )","title":"jsPsych.randomization.repeat"},{"location":"core_library/jspsych-randomization/#parameters_2","text":"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.","title":"Parameters"},{"location":"core_library/jspsych-randomization/#return-value_2","text":"The return value depends on the unpack parameter. See description of the parameter above, and examples below.","title":"Return value"},{"location":"core_library/jspsych-randomization/#description_2","text":"This method takes an array of values and generates a new random order of the array, with the option of repeating each element of the array a specified number of times. If the array elements are objects with the same set of properties, then this method can optionally return a single object where each property is a randomized order of the properties defined in the original set of objects. This is useful for randomizing sets of parameters that are used to define a jsPsych block.","title":"Description"},{"location":"core_library/jspsych-randomization/#examples_1","text":"","title":"Examples"},{"location":"core_library/jspsych-randomization/#shuffle-an-array-no-repeats","text":"var myArray = [ 1 , 2 , 3 , 4 , 5 ]; var shuffledArray = jsPsych . randomization . repeat ( myArray , 1 ); // output: shuffledArray = [3,2,4,1,5]","title":"Shuffle an array, no repeats"},{"location":"core_library/jspsych-randomization/#shuffle-an-array-with-repeats","text":"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]","title":"Shuffle an array with repeats"},{"location":"core_library/jspsych-randomization/#shuffle-an-array-of-objects","text":"var trial1 = { stimulus : 'img/faceA.jpg' , correct_key : 'p' , person_name : 'Joe' } var trial2 = { stimulus : 'img/faceB.jpg' , correct_key : 'p' , person_name : 'Fred' } var trial3 = { stimulus : 'img/faceC.jpg' , correct_key : 'q' , person_name : 'Mary' } var myArray = [ trial1 , trial2 , trial3 ]; var shuffledArray = jsPsych . randomization . repeat ( myArray , 2 ); // output: shuffledArray = [ trial1, trial3, trial3, trial2, trial1, trial2 ]","title":"Shuffle an array of objects"},{"location":"core_library/jspsych-randomization/#shuffle-an-array-of-objects-with-unpack","text":"var trial1 = { stimulus : 'img/faceA.jpg' , correct_key : 'p' , person_name : 'Joe' } var trial2 = { stimulus : 'img/faceB.jpg' , correct_key : 'p' , person_name : 'Fred' } var trial3 = { stimulus : 'img/faceC.jpg' , correct_key : 'q' , person_name : 'Mary' } var myArray = [ trial1 , trial2 , trial3 ]; 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: ['p', 'p', 'q', 'p', 'q', 'p'], person_name: ['Fred', 'Joe', 'Mary', 'Joe', 'Mary', 'Fred'] } */","title":"Shuffle an array of objects, with unpack"},{"location":"core_library/jspsych-randomization/#jspsychrandomizationsamplewithreplacement","text":"jsPsych . randomization . sampleWithReplacement ( array , sampleSize , weights )","title":"jsPsych.randomization.sampleWithReplacement"},{"location":"core_library/jspsych-randomization/#parameters_3","text":"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 .","title":"Parameters"},{"location":"core_library/jspsych-randomization/#return-value_3","text":"An array containing the sample.","title":"Return value"},{"location":"core_library/jspsych-randomization/#description_3","text":"This method returns a sample drawn at random from a set of values with replacement. The relative probability of drawing each item can be controlled by specifying the weights .","title":"Description"},{"location":"core_library/jspsych-randomization/#examples_2","text":"","title":"Examples"},{"location":"core_library/jspsych-randomization/#sample-with-equal-probability","text":"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];","title":"Sample with equal probability"},{"location":"core_library/jspsych-randomization/#sample-with-unequal-probability","text":"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];","title":"Sample with unequal probability"},{"location":"core_library/jspsych-randomization/#jspsychrandomizationsamplewithoutreplacement","text":"jsPsych . randomization . sampleWithoutReplacement ( array , sampleSize )","title":"jsPsych.randomization.sampleWithoutReplacement"},{"location":"core_library/jspsych-randomization/#parameters_4","text":"Parameter Type Description array array The array of values to sample from sampleSize numeric The number of samples to draw","title":"Parameters"},{"location":"core_library/jspsych-randomization/#return-value_4","text":"An array containing the sample.","title":"Return value"},{"location":"core_library/jspsych-randomization/#description_4","text":"This method returns a sample drawn at random from a set of values without replacement. The sample size must be less than or equal to the length of the array.","title":"Description"},{"location":"core_library/jspsych-randomization/#examples_3","text":"","title":"Examples"},{"location":"core_library/jspsych-randomization/#sample-without-replacement","text":"var myArray = [ 1 , 2 , 3 , 4 , 5 ]; var sample = jsPsych . randomization . sampleWithoutReplacement ( myArray , 2 ); // output: sample = [3,2];","title":"Sample without replacement"},{"location":"core_library/jspsych-randomization/#jspsychrandomizationshuffle","text":"jsPsych . randomization . shuffle ( array )","title":"jsPsych.randomization.shuffle"},{"location":"core_library/jspsych-randomization/#parameters_5","text":"Parameter Type Description array array The array of values to shuffle","title":"Parameters"},{"location":"core_library/jspsych-randomization/#return-value_5","text":"Returns an array with the same elements as the input array in a random order.","title":"Return value"},{"location":"core_library/jspsych-randomization/#description_5","text":"A simple method for shuffling the order of an array.","title":"Description"},{"location":"core_library/jspsych-randomization/#examples_4","text":"","title":"Examples"},{"location":"core_library/jspsych-randomization/#shuffle-an-array","text":"var myArray = [ 1 , 2 , 3 , 4 , 5 ]; var shuffledArray = jsPsych . randomization . shuffle ( myArray ); // output: shuffledArray = [3,2,4,1,5]","title":"Shuffle an array"},{"location":"core_library/jspsych-randomization/#jspsychrandomizationshufflenorepeats","text":"jsPsych . randomization . shuffleNoRepeats ( array , equalityTest )","title":"jsPsych.randomization.shuffleNoRepeats"},{"location":"core_library/jspsych-randomization/#parameters_6","text":"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.","title":"Parameters"},{"location":"core_library/jspsych-randomization/#return-value_6","text":"Returns an array with the same elements as the input array in a random order, with no repeating neighbors.","title":"Return value"},{"location":"core_library/jspsych-randomization/#description_6","text":"Shuffle an array, ensuring that neighboring elements in the array are different. Warning: if you provide an array that has very few valid permutations with no neighboring elements, then this method will fail and cause the browser to hang.","title":"Description"},{"location":"core_library/jspsych-randomization/#examples_5","text":"","title":"Examples"},{"location":"core_library/jspsych-randomization/#basic-example","text":"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]","title":"Basic example"},{"location":"core_library/jspsych-randomization/#custom-equalitytest","text":"var myObjects = [ { color : \"blue\" }, { color : \"red\" }, { color : \"yellow\" }, { color : \"orange\" } ]; var repeatedSet = jsPsych . randomization . repeat ( myObjects , 3 ); var shuffled = jsPsych . randomization . shuffleNoRepeats ( repeatedSet , function ( a , b ) { return a . color === b . color }); // console.log(JSON.stringify(shuffled)) // \"[{\"color\":\"red\"},{\"color\":\"yellow\"},{\"color\":\"blue\"},{\"color\":\"yellow\"},{\"color\":\"orange\"},{\"color\":\"red\"},{\"color\":\"yellow\"},{\"color\":\"orange\"},{\"color\":\"blue\"},{\"color\":\"orange\"},{\"color\":\"red\"},{\"color\":\"blue\"}]\"","title":"Custom equalityTest"},{"location":"core_library/jspsych-turk/","text":"jsPsych.turk \u00b6 The jsPsych.turk module contains functions for interacting with Mechanical Turk. jsPsych.turk.submitToTurk \u00b6 jsPsych . turk . submitToTurk ( data ) Parameters \u00b6 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. 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 \u00b6 Returns nothing. Description \u00b6 This method will submit a HIT to Mechanical Turk, causing the HIT to finish. This method will only work when called from within the mechanical turk website. If you are using an external HIT to send workers to your own server, this method will not work on an externally hosted page. It will work if your external content is loaded in the iframe on the Mechanical Turk website. Example \u00b6 < p > Enter the code you were given: < input type = \"text\" id = \"code\" > < button onclick = \"sendData();\" > Submit HIT < script > // this content must be loaded in the iframe on the mechanical turk website. // usually, this means that the content is part of your 'recruitment ad', the // page the workers can see when they are deciding whether or not to accept a HIT. // one option is to include a simple form on this page that workers submit, with a // special code that they get at the end of the experiment. function sendData () { jsPsych . turk . submitToTurk ({ code : document . getElementById ( 'code' ). value }); } jsPsych.turk.turkInfo \u00b6 jsPsych . turk . turkInfo () Parameters \u00b6 None. Return value \u00b6 Returns an object with six properties: .assignmentId contains the assignment ID string of the HIT. .hitId contains the HIT ID. .workerId contains the worker ID of the worker completing the HIT. .turkSubmitTo contains the URL for submitting the HIT. This parameter is used in the jsPsych.turk.submitToTurk method, and is probably not useful outside of that context. .previewMode is a boolean value indicating whether or not the worker has accepted the HIT yet. If the page is viewed inside Mechancial Turk and the worker has not clicked 'Accept HIT' then this will be true. If the page is viewed outside Mechanical Turk or the worker has acccepted the HIT, then it will be false. .outsideTurk is a boolean value indicating if the page is being viewed within Mechanical Turk, or if it is being viewed from another source (e.g., someone directly going to the page URL instead of going through mturk). Description \u00b6 This method returns basic information about the current Mechanical Turk session, including the worker ID, assignment ID, and HIT ID. Example \u00b6 var turkInfo = jsPsych . turk . turkInfo (); alert ( 'Worker ID is: ' + turkInfo . workerId ); alert ( 'Assignment ID is: ' + turkInfo . assignmentId ); alert ( 'HIT ID is: ' + turkInfo . hitId ); // true if the page is viewed within Mechanical Turk, // but worker has not accepted the HIT yet. // false if the page is viewed outside Mechanical Turk, // OR the worker has accepted the HIT. alert ( 'Preview mode? ' + turkInfo . previewMode ); // true if the page is viewed outside mechanical turk, // false otherwise. alert ( 'Outside turk? ' + turkInfo . outsideTurk );","title":"jsPsych.turk"},{"location":"core_library/jspsych-turk/#jspsychturk","text":"The jsPsych.turk module contains functions for interacting with Mechanical Turk.","title":"jsPsych.turk"},{"location":"core_library/jspsych-turk/#jspsychturksubmittoturk","text":"jsPsych . turk . submitToTurk ( data )","title":"jsPsych.turk.submitToTurk"},{"location":"core_library/jspsych-turk/#parameters","text":"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. 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.","title":"Parameters"},{"location":"core_library/jspsych-turk/#return-value","text":"Returns nothing.","title":"Return value"},{"location":"core_library/jspsych-turk/#description","text":"This method will submit a HIT to Mechanical Turk, causing the HIT to finish. This method will only work when called from within the mechanical turk website. If you are using an external HIT to send workers to your own server, this method will not work on an externally hosted page. It will work if your external content is loaded in the iframe on the Mechanical Turk website.","title":"Description"},{"location":"core_library/jspsych-turk/#example","text":"< p > Enter the code you were given: < input type = \"text\" id = \"code\" > < button onclick = \"sendData();\" > Submit HIT < script > // this content must be loaded in the iframe on the mechanical turk website. // usually, this means that the content is part of your 'recruitment ad', the // page the workers can see when they are deciding whether or not to accept a HIT. // one option is to include a simple form on this page that workers submit, with a // special code that they get at the end of the experiment. function sendData () { jsPsych . turk . submitToTurk ({ code : document . getElementById ( 'code' ). value }); } ","title":"Example"},{"location":"core_library/jspsych-turk/#jspsychturkturkinfo","text":"jsPsych . turk . turkInfo ()","title":"jsPsych.turk.turkInfo"},{"location":"core_library/jspsych-turk/#parameters_1","text":"None.","title":"Parameters"},{"location":"core_library/jspsych-turk/#return-value_1","text":"Returns an object with six properties: .assignmentId contains the assignment ID string of the HIT. .hitId contains the HIT ID. .workerId contains the worker ID of the worker completing the HIT. .turkSubmitTo contains the URL for submitting the HIT. This parameter is used in the jsPsych.turk.submitToTurk method, and is probably not useful outside of that context. .previewMode is a boolean value indicating whether or not the worker has accepted the HIT yet. If the page is viewed inside Mechancial Turk and the worker has not clicked 'Accept HIT' then this will be true. If the page is viewed outside Mechanical Turk or the worker has acccepted the HIT, then it will be false. .outsideTurk is a boolean value indicating if the page is being viewed within Mechanical Turk, or if it is being viewed from another source (e.g., someone directly going to the page URL instead of going through mturk).","title":"Return value"},{"location":"core_library/jspsych-turk/#description_1","text":"This method returns basic information about the current Mechanical Turk session, including the worker ID, assignment ID, and HIT ID.","title":"Description"},{"location":"core_library/jspsych-turk/#example_1","text":"var turkInfo = jsPsych . turk . turkInfo (); alert ( 'Worker ID is: ' + turkInfo . workerId ); alert ( 'Assignment ID is: ' + turkInfo . assignmentId ); alert ( 'HIT ID is: ' + turkInfo . hitId ); // true if the page is viewed within Mechanical Turk, // but worker has not accepted the HIT yet. // false if the page is viewed outside Mechanical Turk, // OR the worker has accepted the HIT. alert ( 'Preview mode? ' + turkInfo . previewMode ); // true if the page is viewed outside mechanical turk, // false otherwise. alert ( 'Outside turk? ' + turkInfo . outsideTurk );","title":"Example"},{"location":"extensions/extensions/","text":"Extensions \u00b6 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 \u00b6 To use an extension in an experiment, you'll load the extension file via a