| #javascript, #jQuery

How to call jQuery plugins using the apply() or call() functions

This short post shows how to set the right context for jQuery plugins.

The apply() function is especially useful, if you want to call functions with dynamically generated parameters. The first argument of apply() and call() becomes the this value of the called function.

Since this in the scope of a jQuery plugin is the jQuery element it was called on, the call of a plugin looks like this:

      var $el = $('#anyElement');
      $el.jQPlugin.apply($el, arrayOfArgs);
      $el.jQPlugin.apply($el, arg[, ...]);

$el is cached to avoid double selection. This of course only works, if jQPlugin accepts the arguments in the arrayOfArgs array. Typeahead.js for example accepts a variable number of arguments.

← loom.js
→ Logging in programmatically with Codeception and Symfony2