Open In App

How to create a jQuery plugin with methods?

Jquery is a Javascript library that is built to design or simplifies HTML, CSS, AJAX, DOM as well as event handling for web development. It is Open Source Software and free to all. More than 10 million websites use jquery. Jquery simply converts a line of javascript into methods that can be called in a single line of code. These plugins are implemented. Approach: In Jquery Plug-in is a code that is needed in a standard javascript file. Plugins help in providing different methods that can be used with different jquery library methods.

jQuery.fn.methodName = methodDefinition;

Syntax: Here is the syntax of a plugin file



(function($){
    $.fn.myFunction(settings){
        settings = $.extend({setting_A: 'default_A', setting_B: 'default_B'...});
         ...code away!
    };
}(jQuery);

Example 1: Here is a plug-in example. 




<!DOCTYPE html>
<html>
 
<head>
    <title></title>
    <script src="jquery-3.4.1.js"
            type="text/javascript">
    </script>
 
    <script src="custom.js"
            type="text/javascript">
    </script>
 
</head>
<script>
    (function($) {
 
            $.fn.myFunction(settings) {
 
                settings = $.extend({
                    setting_A: 'default_A',
                    setting_B: 'default_B'...
                });
 
                ...code away!
 
            };
 
        }(jQuery);
</script>
 
<body>
    <h1>GeeksForGeeks</h1>
    <p>A Computer Portal For Geeks</p>
    <button> Click To Get Started </button>
 
    <script>
        $(document).ready(function() {
            $('button').click(function() {
                alert('My first jquery code');
            });
        });
    </script>
</body>
 
</html>

Output:



Example 2: The following method is an example of having a warning method. Just Take a look into the syntax of file plugin.js

(function($) {
    $.fn.targetBlank = function () {
    alert('Working');
}
}) (jQuery);

Now Take a Look into the Example which shows how to link the plugin with HTML 




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet"
          type="text/css"
          href="css/style.css">
</head>
<script>
    (function($) {
        $.fn.targetBlank = function() {
 
            alert('Working');
 
        }
    })(jQuery);
</script>
 
<body>
    <a href="https://www.google.co.in/"
       target="_blank">Google</a>
 
    <script type="text/javascript"
            src="jquery-3.4.1.js"></script>
    <script type="text/javascript"
            src="plugin.js"></script>
    <script type="text/javascript"
            src="ext.js"></script>
</body>
 
</html>

Output:


Article Tags :