Integrating Public Methods and Callbacks
Add public methods to your plugins for external interaction and incorporate callback functions to allow users to hook into specific plugin events.
Integrating Public Methods and Callbacks is a free jQuery Academy lesson on CoddyKit — lesson 3 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the jQuery Academy learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Interact with Your Plugins
Great plugins aren't just standalone. They let users interact with them after initialization! This lesson teaches you how to add public methods for external control and callback functions for custom reactions.
- Public Methods: Functions users can call on an initialized plugin instance.
- Callbacks: Functions that run when specific events happen inside your plugin.
Plugin Basics Revisited
Recall that jQuery plugins are often wrapped in an Immediately Invoked Function Expression (IIFE) to prevent global scope pollution. This structure provides a secure place for your plugin's logic and internal variables.
We'll build upon this familiar pattern.
(function($) {
$.fn.myPlugin = function(options) {
// Default settings
var settings = $.extend({}, $.fn.myPlugin.defaults, options);
return this.each(function() {
var $this = $(this); // The element the plugin is applied to
// Plugin logic goes here
console.log("Plugin initialized on: " + $this.attr('id'));
});
};
// Default options
$.fn.myPlugin.defaults = {
message: "Hello from plugin!"
};
})(jQuery);
// How to use (in HTML <div id="myElement"></div>):
// $('#myElement').myPlugin();What are Public Methods?
A public method is a function exposed by your plugin that can be called from outside its internal scope, even after the plugin has been initialized on an element.
Think of it as a remote control for your plugin. You can tell it to do things like "reset," "update," or "get a value."
Implementing a Public Method
To add public methods, we typically store the plugin's instance data (including its methods) directly on the DOM element using jQuery's .data() method.
Let's create a simple "counter" plugin and add a getValue method.
(function($) {
$.fn.counterPlugin = function(options) {
var settings = $.extend({
initialValue: 0
}, options);
return this.each(function() {
var $this = $(this);
var value = settings.initialValue;
var methods = {
getValue: function() {
return value;
},
increment: function() {
value++;
$this.text(value); // Update display
},
init: function() {
$this.text(value); // Initial display
}
};
// Store methods on the element's data
$this.data('counterPlugin', methods);
methods.init(); // Initialize display
});
};
})(jQuery);
// HTML: <div id="myCounter"></div>
// Usage: $('#myCounter').counterPlugin();
// Later: $('#myCounter').data('counterPlugin').getValue();Calling Public Methods
Once your plugin is initialized and its methods are stored via .data(), you can access and call them directly.
The key is retrieving the stored instance from the element first, then calling the method on that instance.
// Assume counterPlugin from previous scene is loaded
// HTML: <div id="myCounter"></div>
$(document).ready(function() {
// Initialize the plugin
$('#myCounter').counterPlugin({ initialValue: 5 });
// Get the plugin instance
var counterInstance = $('#myCounter').data('counterPlugin');
// Call public methods
console.log("Current value: " + counterInstance.getValue());
counterInstance.increment();
console.log("After increment: " + counterInstance.getValue());
});What are Callbacks?
Callback functions are functions that you pass to your plugin, and the plugin executes them at specific points during its lifecycle or when certain internal events occur.
They allow users to "hook into" your plugin's behavior and add their own custom logic without modifying the plugin's source code.
- Think of them like event listeners for internal plugin actions.
- Common callbacks:
onInit,onChange,onComplete.
Implementing a Callback
To implement a callback, first define it in your plugin's default options. Then, inside your plugin, simply call this function when the relevant event happens, passing any useful data.
Let's extend our counter plugin with an onChange callback.
(function($) {
$.fn.counterPlugin = function(options) {
var settings = $.extend({
initialValue: 0,
onChange: function(newValue) {} // Default empty callback
}, options);
return this.each(function() {
var $this = $(this);
var value = settings.initialValue;
var methods = {
getValue: function() {
return value;
},
increment: function() {
value++;
$this.text(value);
// Call the callback when value changes
settings.onChange.call($this[0], value);
},
init: function() {
$this.text(value);
}
};
$this.data('counterPlugin', methods);
methods.init();
});
};
})(jQuery);
// Usage: See next scene!Passing Callback Functions
Users pass their custom callback functions directly within the plugin's options object during initialization. These functions will then be invoked by the plugin at the appropriate time.
Notice how .call($this[0], value) is used. This sets this inside the callback to the DOM element and passes the new value as an argument.
// Assume counterPlugin with onChange callback is loaded
// HTML: <div id="myCounter"></div>
$(document).ready(function() {
$('#myCounter').counterPlugin({
initialValue: 10,
onChange: function(newValue) {
console.log("Counter changed to: " + newValue + " on element: " + this.id);
if (newValue % 2 === 0) {
$(this).css('color', 'blue');
} else {
$(this).css('color', 'red');
}
}
});
var counterInstance = $('#myCounter').data('counterPlugin');
counterInstance.increment(); // Triggers callback
counterInstance.increment(); // Triggers callback
});Multiple Methods & Callbacks
You can define multiple public methods and several different callbacks to handle various events within your plugin. This creates a flexible and powerful component.
- Public methods let users command the plugin.
- Callbacks let the plugin inform the user's code about what's happening.
(function($) {
$.fn.advancedCounter = function(options) {
var settings = $.extend({
initial: 0,
onIncrement: null, // New callback
onDecrement: null, // New callback
onReset: null // New callback
}, options);
return this.each(function() {
var $this = $(this);
var value = settings.initial;
var methods = {
getValue: function() { return value; },
increment: function() {
value++;
$this.text(value);
if ($.isFunction(settings.onIncrement)) {
settings.onIncrement.call($this[0], value);
}
},
decrement: function() {
value--;
$this.text(value);
if ($.isFunction(settings.onDecrement)) {
settings.onDecrement.call($this[0], value);
}
},
reset: function() {
value = settings.initial;
$this.text(value);
if ($.isFunction(settings.onReset)) {
settings.onReset.call($this[0], value);
}
},
init: function() { $this.text(value); }
};
$this.data('advancedCounter', methods);
methods.init();
});
};
})(jQuery);
// HTML: <div id="myAdvancedCounter"></div>
$(document).ready(function() {
$('#myAdvancedCounter').advancedCounter({
initial: 100,
onIncrement: function(v) { console.log("Inc: " + v); },
onReset: function(v) { console.log("Reset to: " + v); }
});
var inst = $('#myAdvancedCounter').data('advancedCounter');
inst.increment();
inst.reset();
});Public Method & Callback Tips
When designing your plugin's public interface, keep these tips in mind:
- Consistent Naming: Use clear, descriptive names for methods and callbacks.
- Error Handling: Check if callbacks are actually functions before calling them (e.g.,
$.isFunction(settings.onComplete)). - Context: Use
.call()or.apply()to set thethiscontext for callbacks, often to the element the plugin is applied to. - Arguments: Pass relevant data to callbacks (e.g., new value, event object).
Plugin Interaction Quiz
Consider a jQuery plugin initialized on #myElement. The plugin has a public method called doSomething() and an onComplete callback.
Which code snippet correctly calls the public method AND passes a custom callback during initialization?
Recap & Next Steps
You've mastered how to make your jQuery plugins truly interactive and flexible!
- Public methods allow external code to control and query your plugin after it's initialized.
- Callbacks provide hooks for users to inject custom logic, reacting to internal plugin events.
These techniques are crucial for building robust, reusable, and user-friendly jQuery plugins.
Frequently asked questions
Is the “Integrating Public Methods and Callbacks” lesson free?
Yes — the full text of “Integrating Public Methods and Callbacks” is free to read here on the web, and the jQuery Academy course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the jQuery Academy course, upgrade to CoddyKit PRO.
What will I learn in “Integrating Public Methods and Callbacks”?
Add public methods to your plugins for external interaction and incorporate callback functions to allow users to hook into specific plugin events. You practise jQuery Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start jQuery Academy?
No prior experience is required. jQuery Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 3, so you can start here or from the beginning and move at your own pace.
How long does the “Integrating Public Methods and Callbacks” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this jQuery Academy lesson?
Yes. Every jQuery Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Plugin Design Patterns and Scoping
- Building Configurable and Reusable Plugins
- Integrating Public Methods and Callbacks