JQuery Plugin Hello World

From CoderLearner
Jump to: navigation, search

Description

How to write a basis jQuery plugin.

Syntax 1

  • myplugin is the name of the plugin function.
(function($) {
    $.fn.myplugin = function() {
        
    }
}(jQuery));


Syntax 2

  • myplugin2 is the name of the plugin function with input.
  • inputsomething is for the input text
(function($) {
    $.fn.myplugin2 = function(inputsomething) {
        
    }
}(jQuery));


Example 1

This jQuery plugin is used to call to replace the text for each element.

(function($) {
    $.fn.myplugin = function() {
         return this.each(function() {
            $(this).text("this is my function");
        });
    }
}(jQuery));
                

Usage


<!DOCTYPE html>
<html>
    <head>
        <title>Jquery plugin basis</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script src="/junk/jqueryplugin/myplugin.js"></script>

        <script>
            $().ready(function() {
                $('div').myplugin();
            });
        </script>
    </head>
    <body>
        <div>TODO write content</div>
        <div>God blesses you!</div>
    </body>
</html>

Result

this is my function
this is my function

Example 2

(function($) {
    $.fn.myplugin2 = function(inputtext) {
        return this.each(function() {
            $(this).text(inputtext);
        });
    }
}(jQuery));
                

Usage


   <script>
            $().ready(function() {
                $('div').myplugin2('King Vs. Queen');
            });
    </script>