Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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() );
share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

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!");
    };
});
share|improve this answer
    
Thanks! If I omit window., the function assignment code also works. Is it defaulting to the window namespace in this case? –  onemanarmy Nov 13 '12 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 Nov 13 '12 at 20:00
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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