0

I'm using Drupal 7. I have the following code that tries to log to the console:

function mymodule_get_jquery() {
  $jquery = <<<JAVASCRIPT

  console.log("here");

  (function($) {
    console.log("there");

    Drupal.behaviors.addHighStockChart = {

      attach: function(context, settings) {

        console.log("everywhere");

        /* ... */

      } // end attach
    } // end Drupal.behaviors.addHighStockChart
  }) (jQuery);

JAVASCRIPT;

  return $jquery;
}

If I open the Console in Firefox or Chrome, the log outputs the following:

JQMIGRATE: Migrate is installed, version 1.4.1
here
there

Why isn't the "everywhere" line getting logged? Is there any way to log JavaScript info in the Drupal behavior attach function?

UPDATE:

Here is how I am calling the mymodule_get_jquery() function:

/*
 * Implements hook_page().
 */
function mymodule_page() {

  /* ... */

  $jquery = mymodule_get_jquery();
  drupal_add_js($jquery, "inline");

  /* ... */
}    
5
  • 1
    Might be worth including how you're actually adding your JS onto the site with your mymodule_get_jquery() call – Leigh Feb 14 '20 at 16:28
  • I don't think there's ever been a hook_page, did you mean to use hook_page_alter? – Clive Feb 14 '20 at 19:32
  • Well, maybe technically it's not a hook, but I call mymodule_page() in the page callback of my implementation of hook_menu(). – MrSnrub Feb 14 '20 at 19:38
  • There's your problem - hook_menu isn't executed on every page, it's only invoked when the menus are rebuilt. Moving your code into something that gets called on every page like hook_init or hook_page_alter should fix it – Clive Feb 14 '20 at 19:42
  • I misread your comment, calling it in the page callback would be fine in theory. The JS looks fine so maybe behaviours aren't working in general? What do you see for output if you execute Drupal.attachBehaviors() in the console? – Clive Feb 14 '20 at 19:47
-1

Drupal object should be passed as function parameter like below:

(function($, Drupal) {
    console.log("there");

    Drupal.behaviors.addHighStockChart = {

      attach: function(context, settings) {

        console.log("everywhere");

        /* ... */

      } // end attach
    } // end Drupal.behaviors.addHighStockChart
  }) (jQuery, Drupal);
2
  • Thank you for the response, but I'm afraid that did not fix my issue. – MrSnrub Feb 14 '20 at 15:55
  • That might be slightly better practice, but there's no reason you "should" do this - Drupal is in the global scope, so it's going to be available whether you explicitly localise it or not. And it wouldn't fix the OP's issue – Clive Feb 14 '20 at 16:03

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.