0

I am experiencing the following issue within Drupal but it is probably not entirely a Drupal specific issue.

I have the following simple javascript:

(function ($) {

  function testing(){
    alert('TEST function responding!');
  }

})(jQuery);

And I am attempting to call that function from my Drupal module using the following code:

drupal_add_js('jQuery(document).ready(function () { testing(); });',
  array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
);

However, I get an error saying Uncaught ReferenceError: testing is not defined

I want to take advantage of jQuery's abilities within that function which is why I am not using an ordinary JavaScript file.

3 Answers 3

1

Quick and dirty answer: the scope in which you're defining testing() and in which you are calling it are not the same. You could define testing the global scope, and then it will work, although this is not best practice for a large application.

(function ($) {
    window.testing = function(){
        alert('TEST function responding!');
    }
})(jQuery);
Sign up to request clarification or add additional context in comments.

Comments

0

If you want to extend your function to jQuery variable, you can do this:

if( !jQuery.testing ){

jQuery.extend( {
    testing: function() { 
        console.log("Calling from extend function in jQuery");
    }
});
}

And to call it:

drupal_add_js('jQuery(document).ready(function () { jQuery.testing(); });',
  array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
);

Comments

0

Are you storing the first part of the code in an external JavaScript? use drupal_add_js to reference that e.g.,

drupal_add_js('js/external.js');

//external.js
jQuery.noConflict();
jQuery(document).ready(function($) {
window.testing = function(){
    alert('TEST function responding!');
// The useful part of this is the ability to use $ from now on. e.g., $('body').hide();
}
});
});

then add your JavaScript

drupal_add_js('jQuery(document).ready(function () { testing(); });',
array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.