jsPsych icon indicating copy to clipboard operation
jsPsych copied to clipboard

load custom CSS method for pluginAPI

Open jodeleeuw opened this issue 8 years ago • 2 comments

A method to take a block of CSS and add it to the document head in a style tag, and a method to unload the block.


var css_block = jsPsych.pluginAPI.loadCSS('body { background-color: #ff0000; }');
jsPsych.pluginAPI.unloadCSS(css_block);

Works by generating a <style> tag with unique ID, returning either ref to element or ID to grab later.

jodeleeuw avatar Mar 21 '17 02:03 jodeleeuw

Here's my solution:

  module.loadCSS = function(css) {
    /** Loads CSS to a dynamically created stylesheet
     * and returns the id of that stylesheet for later
     * unloading.
     * */
    const random_id = jsPsych.randomization.randomID(20);
    const id = `custom-jspsych-css-${random_id}`;
    const style_sheet = document.createElement("style");
    style_sheet.type = "text/css";
    style_sheet.setAttribute("id", id);
    style_sheet.innerHTML = css;
    document.head.appendChild(style_sheet);
    return id;
  };

  module.unloadCSS = function(id) {
    /** Unloads the stylesheet referenced by id. */
    const style_sheet = document.getElementById(id);
    style_sheet.disabled = true;
    style_sheet.parentNode.removeChild(style_sheet);
  };

stefanuddenberg avatar Feb 18 '20 15:02 stefanuddenberg

This is great @stefanuddenberg . Thanks!

jodeleeuw avatar Feb 18 '20 15:02 jodeleeuw