Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to create a custom jQuery Plugin?

I want to create my own jQuery plugin. How can I create a custom jQuery plugin with a custom name? I have the following div:

<div id="myclass"></div>

I want the result of calling the plugin to get displayed inside the above div.


1 Answer
Amit D

To create a jQuery plugin, firstly create a file named jquery-myplugin.js with the following code. This is our plugin code. Here, myplugin is the name of our plugin.

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

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-myplugin.js"></script>

<script>
$(document).ready(function() {
   $('#myclass').myplugin();
});

</script>
</head>
<body>

<div id="myclass"></div>

</body>
</html>

Run the above code and you can see the text is visible, which shows your custom plugin is working correctly.

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.