Using Ajax-Callback with ajax_command_invoke to invoke custom jQuery command I have a button on a form that when clicked adds an additional subsection to the form via ajax. Now I need to make it so the form automatically scrolls to the start of the newly added content.

I rewrote the ajax callback function so it returns an ajax command array instead of just the changed form data, and added an ajax_command_replace call in the array to still have my content replaced. This works and from the user side everything is unchanged.

Now I found out that I can add an ajax_command_invoke command to have a jQuery function called upon the DOM element I want to interact with. Unfortunately there didn't seem to be an in-built scrollTo jQuery function, so I had to add my own.

This function works when I call it via Firebug, but the ajax callback just gives me an error:


  TypeError: $element[response.method] is undefined
  $element[response.method].apply($element, response.arguments);


So I guess my problem is that my custom jQuery module isn't actually added to jQuery at the time the callback is handled, but only after that?

Here's my configuration (sensitive data hidden with &lt;...&gt;:

Within the Drupal Module, my callback function:

function callback($form,&amp;$form_state) {

  drupal_add_js(drupal_get_path('module', '&lt;...&gt;') . '/js/jquery_plugins.js');

  $commands = array();

  $commands[] = ajax_command_replace(NULL, drupal_render($form[&lt;element&gt;]));
  $commands[] = ajax_command_invoke('&lt;...&gt;', 'scrollTo', array(750));

  return array(
    '#type'     =&gt; 'ajax',
    '#commands' =&gt; $commands
  );

}


In the included file, my jQuery scrollTo function:

(function(jQuery) {
  jQuery.fn.scrollTo = function(data) {
    jQuery('html, body').animate({
      scrollTop: jQuery(this).offset().top
    }, data);
  };
})(jQuery);


Where should I include my jQuery module so the callback knows what I want from it when it's handled?

Update:

I had most of my help until that point from this similar discussion on Drupal.org. It seems to have worked for them.
Using drupal_add_js() in an AJAX callback will (at best) have weird results. Come to think of it I'm not sure I've ever actually seen it work.

The simplest solution is to add the JS in the form function itself, that way it'll always be available regardless of the AJAX state of the page:

function MYMODULE_some_form($form, &amp;$form_state) {
  // Moved from the AJAX callback to here.
  $form['#attached']['js'][drupal_get_path('module', '&lt;...&gt;') . '/js/jquery_plugins.js'] = array();

  // ... Rest of the form
}