Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8122579
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T05:52:45+00:00 2026-06-06T05:52:45+00:00

I have been trying to learn how to build jQuery plugins, so I’m still

  • 0

I have been trying to learn how to build jQuery plugins, so I’m still new at this. Since this is my first plugin, I decided I would try a simple collapsible panel/box (you can only read so much, right?). I’m having difficulty accessing my reference to my Javascript class object when the click event triggers. I know that this inside of the event refers to the element that triggered the event. I also know that I can do something like _self = this; before the event, but that will only cache the last object from the collection. Does anyone have any suggestions on how I can keep a reference to the class object?

Thanks!

Here is my code.

HTML code

<div class="mypanel" title="Panel 1">Testing panel 1</div>
<div class="mypanel" title="Panel 2">Testing panel 2</div>
$('.mypanel').collapsiblePanel();

Plugin code

var contentVisible = 'showContent', contentNotVisible = 'hideContent';

;(function($) {
    var pluginName = 'collapsibleBox';

    function Plugin(element, options) {
        this.ele = element;
        this.$ele = $(element);
        var _self = this;

        this.options = $.extend({}, $.fn[pluginName].defaults, options);

        this.init();

        /* Expose methods of Plugin we wish to be public.
         * This gets stored when the plugin is created
         */
        return {
            option: this.option,
            destroy: this.destroy
            /* Other public methods here */
        }
    }
    $.fn[pluginName] = function(options) {
        /* If the first parameter is a string, treat this as a call to a public method. */
        if(typeof arguments[0] === 'string') {
            var methodName = arguments[0];
            var args = Array.prototype.slice.call(arguments, 1);
            var returnVal;
            this.each(function() {
                /* Check that the element has a plugin instance, and that
                 * the requrested public method exists.
                 */
                if($.data(this, 'plugin_' + pluginName) && typeof $.data(this, 'plugin_' + pluginName)[methodName] === 'function') {
                    /* Call the method of the Plugin instance, and Pass it the supplied arguments */
                    returnVal = $.data(this, 'plugin_' + pluginName)[methodName].appy(this, args);
                }
                else {
                    $.error('Method ' + methodName + ' does not exist on jQuery.' + pluginName);
                }
            });
            if(returnVal !== undefined) {
                /* If the method returned something, return it */
                return returnVal;
            }
            else {
                /* Otherwise, returning 'this' preserves chainability */
                return this;
            }
        }
        /* If the first parameter is an object (options), or was omitted,
         * instantiate a new instance of the plugin
         */
        else if(typeof options === 'object' || !options) {
            return this.each(function() {
                /* Only allow the plugin to be instantiated once */
                if(!$.data(this, 'plugin_' + pluginName)) {
                    /* Pass options to Plugin constructor, and store Plugin
                     * instance in the element's jQuery data object
                     */
                    $.data(this, 'plugin_' + pluginName, new Plugin(this, options));
                }
            });
        }
    };

    $.fn[pluginName].defaults = {
        onInit: function() {},
        onDestroy: function() {}
    };

    Plugin.prototype = {
        init: function() {
            this.createContentArea();
            this.createTitleBar();
            this.hook('onInit');
        },
        createContentArea: function() {
            /* ... */
        },
        createTitleBar: function() {
            /* ... */

            this.$title.click(function() {
                if(this.$ele.data('state') == contentVisible) { // The problem is here
                    this.collapse();
                }
                else {
                    this.expand();
                }
            });
        },
        expand: function() {
            this.$content.slideDown();
            this.$ele.data('state', contentVisible);
        },
        collapse: function() {
            console.log(this);
            this.$content.slideUp();
            this.$ele.data('state', contentNotVisible);
        },
        /* Use this function to get/set variables */
        option: function (key, val) {
            if(val) {
                this.options[key] = val;
            }
            else {
                return this.options[key];
            }
        },
        destroy: function () {
            /* ... */
        },

        hook: function (hookName) {
            if(this.options[hookName] !== undefined) {
                this.options[hookName].call(this.ele);
            }
        }
    };
})(jQuery);
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-06T05:52:47+00:00Added an answer on June 6, 2026 at 5:52 am

    I have managed to fix this issue using a combination of the .data() method and the .call() method to ensure that the context of the function call is always the parent element. I managed to get this working using the pattern I had as well as using the pattern suggested by the jQuery Plugin Authoring Tutorial. Whether this was the correct way to do it or not, I don’t know.

    var methods = {
        init: function(options) {
            var $this = $(this), data = {};
            /* Set a local copy of the options */
            data.options = $.extend({}, defaults, options);
            /* Create the content area */
            data.$content = createContentArea(this);
            /* Create the title bar */
            data.$title = createTitleBar(this, data.options.header, data.options.title);
    
            /* Show/Hide the content based on the default state passed in */
            if(data.options.defaultState == contentVisible) {
                data.$content.show();
                data.state = contentVisible;
            }
            else {
                data.$content.hide();
                data.state = contentNotVisible;
            }
    
            /* Add the title click event */
            data.$title.click(function() {
                methods.toggle.call($(this).parent());
            });
    
            /* Add the public methods */
            data.methods = {
                toggle: methods.toggle, 
                expand: methods.expand, 
                collapse: methods.collapse
            };
            return data;
        }, 
        toggle: function() {
            var $this = $(this), data = $this.data('plugin_' + pluginName);
            if(data.state == contentVisible) {
                methods.collapse.call(this);
            }
            else if(data.state == contentNotVisible) {
                methods.expand.call(this);
            }
        }, 
        expand: function() {
            var $this = $(this), data = $this.data('plugin_' + pluginName);
            data.$content.slideDown();
            data.state = contentVisible;
            $this.data('plugin_' + pluginName, data);
        }, 
        collapse: function() {
            var $this = $(this), data = $this.data('plugin_' + pluginName);
            data.$content.slideUp();
            data.state = contentNotVisible;
            $this.data('plugin_' + pluginName, data);
        }
    };
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Ok, this may have been answered, but I'm new and trying to learn, so
I have been trying to learn Prolog and came across this syntax on some
I have been trying to learn Erlang and have been running into some problems
I have been trying to learn a cross platform language with a fast learning
Hi I have been trying to learn Javascript using codeacademy.com and I have reached
I am trying to learn assembly my self, and I have been reading different
I am currently trying to learn Android. Have been reading tutorials and manual for
I have been trying this for a little while nut just cannot get to
I've been trying to learn GWT for quite a while, I want to build
I have been trying to learn horizontal lists in html. I have the following

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.