jQuery

How to Create a Custom jQuery Plugin

Last updated: 10.10.2025
Views: 261

The convenience of the jQuery plugin is that you can use the same code several times for different objects. In this case, copy-paste code is not needed. In addition, you can change the behavior of the plugin with different parameters. To write your jQuery plugin, you need to expand the $.fn object

In general, it looks like this:

$.fn.MyPlugin = function() {
    //plugin code
}

We write a plugin that will add a paragraph with the class “paragraph” after the selected object by clicking on it. By default we will set the red color of the text of our paragraph.

(($) => {
    $.fn.myPlugin = function(options) {
        const settings = $.extend({ //set default parameters
            color: 'red'
        }, options);

        //write the logic of our plugin
        $(this).on('click', function() {

            const par = '<p class="paragraph">An added paragraph</p>';
            $(this).after(par);
            $(this).next('.paragraph').css('color', settings.color);

        });

        return this; //for call chains
    }
})(jQuery);

The call for two different elements looks like this:

$(() => {
 
    $('.firstsel').myPlugin({
        color: 'green'
    });
     
    $('.secondsel').myPlugin();
     
});

You can see an example of how this works on Codepen:  https://codepen.io/igorrybalko/pen/WberZOY

author
Author: Igor Rybalko
I have been working as a front-end developer since 2014. My main technology stack is Vue.js and WordPress.

Similar posts:

  • Vue Accordion Component
    A simple and lightweight Vue 3 accordion component plugin. Supports both global plugin registration and local component usage. Written in TypeScript. The accordion compon...
  • Drop down menu (jQuery)
    Drop down menu can be done without JavaScript, only with the help of CSS. With :hover. But the JavaScript menu has its advantages. The most important thing is the delay i...
  • jQuery Accordion Plugin
    An accordion is often used on websites. This element is popular and convenient at the same time. An accordion helps to structure content and save space. In my work, I oft...

Leave a Reply

Your email address will not be published. Required fields are marked *