0

I get a method not defined error when trying to call a function loaded with wp_enqueue_script from site.js.

I'm guessing it's because of scope caused by the jQuery ready wrappers? How do I get around that?

site.js (loaded in head)

jQuery(document).ready(function($) {
  $(window).load(function() { // wait until everything has loaded
    doSomething(); // results in face palm
  });
});

my-script.js (loaded in footer)

jQuery(document).ready(function($) {

  function doSomething() {
    alert("Time for a coffee break!");
  }
});

functions.php

wp_register_script( 'my-script', get_template_directory_uri().'/js/my-script.js', array( 'jquery' ), '', true );
wp_enqueue_script( 'my-script' );
// Pass in PHP variables
wp_localize_script( 'my-script', 'my_script', localize_post_vars() );

1 Answer 1

3

You need to put your doSomething in the correct namespace, or at least in a namespace. The simplest way would be to put it in the window namespace:

jQuery(document).ready(function($) {
    window.doSomething = function() {
        alert("Time for a coffee break!");
    };
});
2
  • Thanks! If I omit window., the function assignment code also works. Is it defaulting to the window namespace in this case?
    – manafire
    Commented Nov 13, 2012 at 19:33
  • Yep, to force the variable to be local you would just add var in front of the declaration: var doSomething = function() { ... };.
    – totels
    Commented Nov 13, 2012 at 20:00

Your Answer

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

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