How to write a custom jQuery plugin?

To create a jQuery plugin, first create a file named jquery-demoplugin.js with the following code. This is our plugin code. Here, demoplugin is the name of our plugin. You can add any name to your custom plugin ?

(function ( $ ) {
    $.fn.demoplugin = function( options ) {
        var web = $.extend({
            name: 'example'
        }, options );
        return this.append('Website: ' + web.name + '.com');
    };
}( jQuery ));

The plugin uses the Immediately Invoked Function Expression (IIFE) pattern to avoid namespace conflicts. The $.extend() method merges the default options with user-provided options, allowing customization of the plugin behavior.

Example

Now, to load it, add to the HTML file, new.html ?

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="jquery-demoplugin.js"></script>
    <script>
        $( document ).ready(function() {
            $( '#content' ).demoplugin();
        });
    </script>
</head>
<body>
    <div id="content"></div>
</body>
</html>

The output of the above code is ?

Website: example.com

You can also pass custom options to override the default values ?

$( '#content' ).demoplugin({ name: 'tutorialspoint' });

This would output: Website: tutorialspoint.com

Conclusion

Creating a custom jQuery plugin involves wrapping your functionality in an IIFE and extending the $.fn object. This approach ensures your plugin integrates seamlessly with jQuery's chaining mechanism and avoids global namespace pollution.

Updated on: 2026-03-13T17:44:25+05:30

335 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements