Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to call a function inside a jQuery plugin from outside?
When building jQuery plugins, you often need to expose internal methods so they can be called from outside the plugin. This is achieved by returning an object containing the methods you want to make publicly accessible.
Basic Plugin Structure
A jQuery plugin that exposes methods typically follows this pattern − it returns an object with the functions you want to access externally ?
$.fn.pluginName = function(options) {
var settings = $.extend({
// default options
}, options);
// Return object with public methods
return {
method1: function() { /* ... */ },
method2: function() { /* ... */ }
};
};
Complete Example
Here's a complete example showing how to create a person plugin with methods that can be called externally ?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$.fn.person = function(prop) {
var defaults = $.extend({
name: 'Amit'
}, prop);
// methods to be used outside of the plugin
var person = {
changeName: function(name) {
defaults.name = name;
},
getName: function() {
return defaults.name;
}
};
return person;
};
$(document).ready(function() {
// set initial properties
var person = $('#person').person({
name: 'Sachin'
});
$('#output').html('Initial name of person: ' + person.getName());
person.changeName('Amit');
// printing new name
$('#output').append('<br>Changed name of person: ' + person.getName());
});
</script>
</head>
<body>
<div id="person">Person Plugin Demo</div>
<div id="output"></div>
</body>
</html>
Initial name of person: Sachin Changed name of person: Amit
How It Works
The plugin works by:
-
Extending defaults:
$.extend()merges default options with user-provided options -
Creating public methods: The
personobject contains methods that can access the plugin's internal state -
Returning the interface: By returning the
personobject, external code can call its methods -
Maintaining state: The
defaultsvariable maintains the plugin's internal state
Key Points
When designing plugins with external access:
- Return an object containing the methods you want to expose
- Use closures to maintain private state within the plugin
- Store the returned object in a variable to call its methods
- Avoid using
document.write()in modern applications − use DOM manipulation instead
Conclusion
To call functions inside a jQuery plugin from outside, return an object containing the methods you want to expose. This approach uses JavaScript closures to maintain state while providing a clean public interface.
---