JQuery Plugin Options

From CoderLearner
Jump to: navigation, search


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() {

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

Usage 1

  • Use default values except the color option.

<!DOCTYPE html>
        <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>

            $().ready(function() {
                    color: 'blue'
        <div>TODO write content</div>
        <div>God blesses you!</div>



Usage 2

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