I have a custom module and in it's .module file I add a value to Drupal settings:

  $variables['#attached']['drupalSettings']['my module']['color_body'] = '#dd0000';

I have a named js function and try to access the value:

function loadcal() {
  var backgroundColor = drupalSettings.mymodule.color_body;

I receive the error:

Uncaught TypeError: Cannot read properties of undefined (reading 'my module')
at Object.attach (loadcal.js?rb7yo3:52:37)

All of the working examples of using drupalSettings seem to be with anonymous functions:

(function ($) {}

I can refactor to do this as a DOMready function, but would prefer this function to be callable. I have tried:

(function loadcal($) {}

but that leaves loadcal() not being found when it is called.


I decided I could do without the function being named. I could pass what I needed at the start and not have to make subsequent calls. Here is the code involved:


      css/calendar.css: {}
    js/loadcal.js: { weight: -18 }
    - core/Drupal
    - core/jQuery
    - core/drupalSettings


function mymodule_preprocess_node($variables) {
  $config = \Drupal::config('mymodule.settings');
  $variables['#attached']['library'][] = 'mymodule/mymodule.calendar';
  $variables['#attached']['drupalSettings']['mymodule']['color_body'] = '#dd0000';


(function (Drupal, drupalSettings, once) {
  Drupal.behaviors.mymodule = {
    attach: function (context, settings) {
      var calendar = new FullCalendar.Calendar(calendarEl, {
        dayCellDidMount: ({date, el}) => {
          el.style.backgroundColor = drupalSettings.mymodule.color_body;

The console error is:

Uncaught TypeError: Cannot read properties of undefined (reading 'color_body')

though when checking drupalSettings, and settings under Closure (attach), or Closure.drupalSettings, mymodule isn't there, though it shows up under Drupal.behaviors.

  • Why the space in 'my module'?
    – Clive
    May 1, 2022 at 20:55
  • The exception message doesn't match the shown code. With drupalSettings.mymodule, it should not complain about reading the my module property of undefined.
    – apaderno
    May 1, 2022 at 21:00
  • 1
    You can either use (function ($) { /* code */ })(jQuery) or (function loadcal($) { /* code */ })(jQuery). The latter would be helpful if that function calls itself (which doesn't usually happen with Drupal behaviors).
    – apaderno
    May 1, 2022 at 21:20
  • This will probably come down to how you're including the JS in the page or how/when you're invoking loadcal()
    – Clive
    May 1, 2022 at 21:31
  • @Clive Yes, that's true. We need to see more code, but so far this seems a plain JavaScript question.
    – apaderno
    May 1, 2022 at 21:39


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.