ajax_command_invoke is a powerful function in Drupal 7 that allows you to invoke JavaScript methods on DOM elements after an AJAX callback. These code examples will show you through setting up a custom module to demonstrate this functionality.
AJAX Callback: The mymodule_ajax_callback function returns an AJAX command to invoke a JavaScript method on a specific DOM element.
Source code viewer
/** * AJAX callback function. */ function mymodule_ajax_callback() { // Add a command to invoke a JavaScript method on a specific element. // Return the commands as a JSON response. } /** * Implements hook_form_alter(). */ function mymodule_form_alter(&$form, &$form_state, $form_id) { if ($form_id == 'your_form_id') { '#type' => 'button', '#value' => t('Click me'), 'callback' => 'mymodule_ajax_callback', 'wrapper' => 'my-element-wrapper', 'method' => 'replace', 'effect' => 'fade', ), ); '#type' => 'markup', '#markup' => '<div id="my-element">Original Content</div>', ); } }Programming Language: PHP
JavaScript Behavior: The JavaScript file defines a custom method myCustomMethod using $.fn to ensure it's available on jQuery objects. This method is then invoked on the element with ID #my-element.
Source code viewer
(function ($) { Drupal.behaviors.myModuleBehavior = { attach: function (context, settings) { // Ensure the element exists in the current context. $('#my-element', context).once('myModuleBehavior', function () { // Define the custom method on the element using jQuery's fn. $.fn.myCustomMethod = function (arg1, arg2) { console.log('Method invoked with arguments:', arg1, arg2); // Perform some action, e.g., update the element's content. this.text('Updated with ' + arg1 + ' and ' + arg2); }; // Invoke the method to ensure it's attached correctly. $(this).myCustomMethod('initial', 'setup'); }); } }; })(jQuery);Programming Language: ECMAScript