JQuery Plugin Options

From CoderLearner
Jump to: navigation, search

Description

Write a complete jQuery plugin with a customizable options.

Example 1 (myplugin.js)

  • myplugin is the name of the plugin function.
  • options is the object for user input variables and default option.
  • $.extend is important, and it uses to establish the variables and its default value.
  • settings variable merged the default value with the user supply parameter values.
(function($) {
    $.fn.myplugin = function(options) {

// setting the default and user define opiton
        var settings = $.extend({
            text: 'hello',
            color: null,
            fontsize: '12px'
        }, options);

        
        return this.each(function() {
            $(this).text(settings.text);

            if (settings.color) {
                $(this).css('color', settings.color);
            }
            $(this).css('font-size', settings.fontsize);
        });
    }
}(jQuery));
                            

Usage 1

  • Use default values except the color option.

<!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({
                    color: 'blue'
                });
            });
        </script>
    </head>
    <body>
        <div>TODO write content</div>
        <div>God blesses you!</div>
    </body>
</html>

Result

hello
hello

Usage 2

       $().ready(function() {
                $('div').myplugin({
                    color: 'blue',
                    text: 'God Sees you eat',
                    fontsize: '18px'
                });
        });