Fisu Fisu - 1 year ago 80
Javascript Question

Calling a function inside a jQuery plugin from outside

I am trying to work out how to call functions within my jQuery plugin from outside the plugin. The code I have tried is not working. I'm sure I will have to restructure my plugin to allow this, but I'm not sure how to. In this example, I'm trying to access the



jQuery plugin

(function($) {
"use strict";

$.fn.testPlugin = function(options) {

// Settings
var settings = $.extend({
newText : "Yabadabado"
}, options);

return this.each(function(i, el) {

var init = function(callback) {
if( $(el).attr("class") === "red" ) {


if( callback && typeof(callback) === "function" ) {

var underline = function() {



Assign the plugin to selectors

var doTest = $("#testItem").testPlugin({
newText: "Scoobydoo"

var doNewTest = $("#newTestItem").testPlugin({
newText: "kapow!"

Call a function that is located within the plugin

$("#underline").click(function(e) {

Answer Source

Take a look at closures.

Here is a basic example of what a closure looks like in a jQuery plugin.

$.fn.plugin = function() {

    return {
        helloWorld: function() {
            console.log('Hello World!');

// init plugin.
var test = $('node').plugin();

// call a method from within the plugin outside of the plugin.

You can see another example at the following jsfiddle.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download