Search

jQueryプラグインの基本テンプレート

unknown

$.fn.pluginName = function(){};
jquery.basic.js
(function($){
    /* プラグイン名(myplugin)を指定 */
    /* 関数にオプション変数を渡す */
    $.fn.myplugin=function(config){
        /* 引数の初期値を設定(カンマ区切り) */
        var defaults={
            defColor:"#ff6699",
            defPadding:5
        }
        var options=$.extend(defaults, config);
        /* 一致した要素上で繰り返す */
        return this.each(function(i){
            /* プラグイン内での現在の要素はthisで参照 */
            $(this).text(this.tagName+"["+i+"]").css({"color":defaults.defColor,"padding":defaults.defPadding});
        });
    };
})(jQuery);
設置サンプルサンプルを見る
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta http-equiv="Content-Language" content="ja" />
        <meta http-equiv="Content-Script-Type" content="text/javascript" />
        <meta http-equiv="Content-Style-Type" content="text/css" />
        <meta http-equiv="imagetoolbar" content="no" />
        <title>設置サンプル</title>
        <link rel="stylesheet" href="/content/lib/global.css" type="text/css" />
        <!-- JS -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
        <script type="text/javascript" src="include/ajax/jquery_plugin/jquery.basic.js"></script>
        <script type="text/javascript">
        $(function(){
            $('li').myplugin();
        });
        </script>
    </head>
    <body>
        <div id="wrap">
            <p>参照:<a href='http://net.tutsplus.com/videos/screencasts/you-still-cant-create-a-jquery-plugin/'>You Still Can’t Create a jQuery Plugin?</a></p>
<!-- CODE -->
            <ul>
                <li>Item1</li>
                <li>Item2</li>
                <li>Item3</li>
            </ul>
<!-- CODE / -->
        </div>
    </body>
</html>

A Really Simple jQuery Plugin Tutorial

unknown

A Really Simple jQuery Plugin Tutorial

アニメーションするナビゲーションメニューを例に、jQueryでプラグインを作成する方法がわかりやすく掲載されています。

通常の記述サンプルを見る
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta http-equiv="Content-Language" content="ja" />
        <meta http-equiv="Content-Script-Type" content="text/javascript" />
        <meta http-equiv="Content-Style-Type" content="text/css" />
        <meta http-equiv="imagetoolbar" content="no" />
        <title>設置サンプル</title>
        <link rel="stylesheet" href="/content/lib/global.css" type="text/css" />
        <!-- JS -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
        <script type="text/javascript">
        $(function(){
            /* リスト要素の奇数行に「even」クラスを追加 */
            $("ul#menu li:even").addClass("even");
            /* マウスオーバーした時にアニメーション */
            $("ul#menu li a").mouseover(function(){
                $(this).animate({paddingLeft:"20px"},{queue:false,duration:500});
            /* マウスが離れた時にアニメーション */
            }).mouseout(function(){
                $(this).animate({paddingLeft:"0",fontSize:"12px"},{queue:false,duration:500});
            /* クリックした時にアニメーション */
            }).click(function(){
                $(this).animate({fontSize:"20px"},{queue:false,duration:500});
                return false;
            });
        });
        </script>
        <!-- CSS -->
        <style type="text/css">
            #menu { list-style:none; margin:0; padding:0; }
            #menu li { list-style:none; margin:0; padding:0 0 0 10px; display:block; width:200px; background-color:#ddd; }
            #menu li a { list-style:none; padding:0; display:block; width:200px; height:30px; line-height:30px; font-size:12px; }
            #menu li.even { background-color:#ccc; }
        </style>
    </head>
    <body>
        <div id="wrap">
            <p>参照:<a href='http://www.queness.com/post/112/a-really-simple-jquery-plugin-tutorial'>A Really Simple jQuery Plugin Tutorial</a></p>
<!-- CODE -->
            <ul id="menu">
                <li><a href="#">MENU1</a></li>
                <li><a href="#">MENU2</a></li>
                <li><a href="#">MENU3</a></li>
                <li><a href="#">MENU4</a></li>
                <li><a href="#">MENU5</a></li>
            </ul>
<!-- CODE / -->
        </div>
    </body>
</html>

ナビゲーションメニューにアニメーションさせる部分をjQueryプラグイン化し、別ファイルにします。

jquery.animatemenu.js
(function($){
    /* jQueryに新しいメソッドを付加 */
    $.fn.extend({
        /* プラグイン名(animateMenu)を指定 */
        /* 関数にオプション変数を渡す */
        animateMenu:function(){
            /* 引数の初期値を設定(カンマ区切り) */
            var defaults={
                animatePadding:60,
                defaultPadding:10,
                mouseOverColor:"#ccc",
                mouseoutColor:"#ddd"
            }
            var options=$.extend(defaults, options);
            /* 一致した要素上で繰り返す */
            return this.each(function(){
                /* 繰り返し処理 */
                var o=options;
                /* 現在の要素を変数に格納、この場合はul要素 */
                var obj=$(this);
                /* ul要素内のli要素を取得 */
                var items=$("li",obj);
                /* 偶数、奇数行にそれぞれ色を指定 */
                $("li:even",obj).css("background-color",o.mouseOverColor);
                $("li:odd",obj).css("background-color",o.mouseoutColor);
                /* li要素にマウスオーバー、マウスアウトした時にアニメーション */
                items.mouseover(function(){
                    $(this).animate({paddingLeft:o.animatePadding},300);
                }).mouseout(function(){
                    $(this).animate({paddingLeft:o.defaultPadding},300);
                });
            });
        }
    });
    /* jQueryに関数を渡す */
})(jQuery);

その別ファイルをhead要素内で読み込み、DOMの操作が可能になった時に、ナビゲーションメニューに対しアニメーション効果を行う処理を実行します。

jQueryプラグインとして記述サンプルを見る
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta http-equiv="Content-Language" content="ja" />
        <meta http-equiv="Content-Script-Type" content="text/javascript" />
        <meta http-equiv="Content-Style-Type" content="text/css" />
        <meta http-equiv="imagetoolbar" content="no" />
        <title>設置サンプル</title>
        <link rel="stylesheet" href="/content/lib/global.css" type="text/css" />
        <!-- JS -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
        <script type="text/javascript">
        $(function(){
            /* リスト要素の奇数行に「even」クラスを追加 */
            $("ul#menu li:even").addClass("even");
            /* マウスオーバーした時にアニメーション */
            $("ul#menu li a").mouseover(function(){
                $(this).animate({paddingLeft:"20px"},{queue:false,duration:500});
            /* マウスが離れた時にアニメーション */
            }).mouseout(function(){
                $(this).animate({paddingLeft:"0",fontSize:"12px"},{queue:false,duration:500});
            /* クリックした時にアニメーション */
            }).click(function(){
                $(this).animate({fontSize:"20px"},{queue:false,duration:500});
                return false;
            });
        });
        </script>
        <!-- CSS -->
        <style type="text/css">
            #menu { list-style:none; margin:0; padding:0; }
            #menu li { list-style:none; margin:0; padding:0 0 0 10px; display:block; width:200px; background-color:#ddd; }
            #menu li a { list-style:none; padding:0; display:block; width:200px; height:30px; line-height:30px; font-size:12px; }
            #menu li.even { background-color:#ccc; }
        </style>
    </head>
    <body>
        <div id="wrap">
            <p>参照:<a href='http://www.queness.com/post/112/a-really-simple-jquery-plugin-tutorial'>A Really Simple jQuery Plugin Tutorial</a></p>
<!-- CODE -->
            <ul id="menu">
                <li><a href="#">MENU1</a></li>
                <li><a href="#">MENU2</a></li>
                <li><a href="#">MENU3</a></li>
                <li><a href="#">MENU4</a></li>
                <li><a href="#">MENU5</a></li>
            </ul>
<!-- CODE / -->
        </div>
    </body>
</html>

Learn How to Create a jQuery Plugin

unknown

Learn How to Create a jQuery Plugin

ブラウザのウィンドウがリサイズしても、常にページ中央に要素を配置するjQueryプラグインを作成する方法が掲載されています。

center.jQuery.js
(function($){
    $.fn.center=function(){
        /* 現在の要素をelementに格納 */
        var element=this;
        /* 現在の要素が読込まれた時にCSSを変更 */
        $(element).load(function(){
            changeCSS();
            /* ウィンドウがリサイズされた時にもCSSを変更 */
            $(window).bind("resize", function(){
                changeCSS();
            });
            /* CSSを変更 */
            function changeCSS(){
                /* 要素の幅・高さを取得 */
                var imageWidth = $(element).width();
                var imageHeight = $(element).height();
                /* ウィンドウの幅・高さを取得 */
                var windowWidth = $(window).width();
                var windowHeight = $(window).height();
                /* 要素のスタイルを変更(要素を常に画面中央に配置) */
                $(element).css({
                    "position" : "absolute",
                    "left" : windowWidth / 2 - imageWidth / 2,
                    "top" : windowHeight /2 - imageHeight / 2
                });
            };
        });
    };
})(jQuery);
設置サンプルサンプルを見る
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta http-equiv="Content-Language" content="ja" />
        <meta http-equiv="Content-Script-Type" content="text/javascript" />
        <meta http-equiv="Content-Style-Type" content="text/css" />
        <meta http-equiv="imagetoolbar" content="no" />
        <title>設置サンプル</title>
        <link rel="stylesheet" href="/content/lib/global.css" type="text/css" />
        <!-- JS -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
        <script type="text/javascript" src="include/ajax/jquery_plugin/center.jQuery.js"></script>
        <script type="text/javascript">
        $(function(){
            /* ウィンドウをリサイズしても、常に画面の中央に画像を配置 */
            $('img').center();
        });
        </script>
        <!-- CSS -->
        <style type="text/css">
            img { border:5px solid #c49f82; }
        </style>
    </head>
    <body>
        <div id="wrap">
            <p>参照:<a href='http://net.tutsplus.com/videos/screencasts/learn-how-to-create-a-jquery-plugin/'>Learn How to Create a jQuery Plugin</a></p>
<!-- CODE -->
            <img src="http://farm4.static.flickr.com/3244/3142386073_87c62671a5_m.jpg" width="240" height="180" alt="Starbucks Coffee 新宿サザンテラス店 " />
<!-- CODE / -->
        </div>
    </body>
</html>

You Still Can’t Create a jQuery Plugin?

unknown

You Still Can’t Create a jQuery Plugin?

tooltipクラスを持つa要素にマウスオーバーすると、そのa要素のtitle属性の内容をツールチップ表示するjQueryプラグインを作成する方法が掲載されています。

jQuery.tooltip.js
(function($){
    /* プラグイン名(tooltip)を指定 */
    /* 関数にオプション変数を渡す */
    $.fn.tooltip=function(options){
        /* 引数の初期値を設定(カンマ区切り) */
        var defaults={
            background:"#e3e3e3",
            color:"black",
            rounded:false
        }
        settings=$.extend({}, defaults, options);
        /* 一致した要素上で繰り返す */
        this.each(function(){
            /* 現在の要素を$thisに格納。この場合はtooltipクラスを持つa要素 */
            var $this=$(this);
            /* 現在の要素のtitle属性の値を格納 */
            var title=this.title;
            if($this.is("a") && $this.attr("title")!=""){
                this.title="";
                $this.hover(function(e){
                    /* マウスオーバー時にツールチップとして表示する要素を生成し、フェードインしながら表示 */
                    $('<div id="tooltip" />')
                    .appendTo("body")
                    .text(title)
                    .hide()
                    .css({
                        backgroundColor: settings.background,
                        color: settings.color,
                        top: e.pageY + 10,
                        left: e.pageX + 20
                    })
                    .fadeIn(350);
                    if(settings.rounded){
                        /* オプションでrounded(角丸)が指定されている場合は、ツールチップとして表示する要素にroundedクラスを追加 */
                        $('#tooltip').addClass('rounded');
                    }
                },function(){
                    /* マウスアウト時にツールチップとして表示した要素を削除する */
                    $('#tooltip').remove();
                });
            }
            /* マウスが移動されたら、それに合わせてツールチップの位置を移動する */
            $this.mousemove(function(e) {
                $("#tooltip").css({
                    top:e.pageY+10,
                    left:e.pageX+20
                });
            });
        });
        /* jQueryオブジェクトを返す */
        return this;
    }
})(jQuery);
設置サンプルサンプルを見る
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta http-equiv="Content-Language" content="ja" />
        <meta http-equiv="Content-Script-Type" content="text/javascript" />
        <meta http-equiv="Content-Style-Type" content="text/css" />
        <meta http-equiv="imagetoolbar" content="no" />
        <title>設置サンプル</title>
        <link rel="stylesheet" href="/content/lib/global.css" type="text/css" />
        <!-- JS -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
        <script type="text/javascript" src="include/ajax/jquery_plugin/jQuery.tooltip.js"></script>
        <script type="text/javascript">
        $(function(){
            $('#exp1 a.tooltip').tooltip();
            $('#exp2 a.tooltip').tooltip({
                rounded: true
            });
        });
        </script>
        <!-- CSS -->
        <style type="text/css">
            #tooltip {
                background:transparent url("/content/img/icon/24/zoom.png") no-repeat 0 0;
                border:1px solid #bfbfbf;
                float: left;
                font-size:12px;
                width:30%;
                padding:1em 1em 1em 60px;
                position:absolute;
            }
            .rounded {
                -moz-border-radius:10px;
                -webkit-border-radius:10px;
            }
        </style>
    </head>
    <body>
        <div id="wrap">
            <p>参照:<a href='http://net.tutsplus.com/videos/screencasts/you-still-cant-create-a-jquery-plugin/'>You Still Can’t Create a jQuery Plugin?</a></p>
<!-- CODE -->
            <h2>デフォルト</h2>
            <blockquote id="exp1">
                <dl>
                   <dt>Ajax</dt>
                   <dd>
                      <p>Ajax(アジャックス、エイジャックス)は、ユーザーインターフェース構築技術の総称。<a class="tooltip" href="#" title="XMLHttpRequest|JavaScriptなどのウェブブラウザ搭載のスクリプト言語で、サーバとのHTTP通信を行うための組み込みオブジェクト(API)">XMLHttpRequest</a>(HTTP通信を行うためのJavaScript組み込みクラス)による非同期通信を利用し、
                         通信結果に応じて<a class="tooltip" href="#" title="DHTML|DHTML(Dynamic HTML)は静的なHTMLの内容をCSSとJavaScript等のクライアントサイドスクリプト言語を用いて動的に変更するウェブ技術を指す抽象概念。">DHTML</a>で動的にページの一部を書き換えるというアプローチを取る。</p>
                         <p>AjaxはAsynchronous (アシンクロナス/エイシンクロナス、非同期) JavaScript + <span title="XML|Extensible Markup Language (エクステンシブルマークアップランゲージ)。">XML</span>の略で、2005年2月18日にJesse James Garrettにより名付けられた。</p>
                        <cite><a href="http://ja.wikipedia.org/wiki/Ajax"><strong>Ajax</strong> From Wikipedia</a></cite>
                      </dd>
                </dl>
            </blockquote>

            <h2>オプション指定(rounded)</h2>
            <blockquote id="exp2">
                <dl>
                   <dt>Ajax</dt>
                   <dd>
                      <p>Ajax(アジャックス、エイジャックス)は、ユーザーインターフェース構築技術の総称。<a class="tooltip" href="#" title="XMLHttpRequest|JavaScriptなどのウェブブラウザ搭載のスクリプト言語で、サーバとのHTTP通信を行うための組み込みオブジェクト(API)">XMLHttpRequest</a>(HTTP通信を行うためのJavaScript組み込みクラス)による非同期通信を利用し、
                         通信結果に応じて<a class="tooltip" href="#" title="DHTML|DHTML(Dynamic HTML)は静的なHTMLの内容をCSSとJavaScript等のクライアントサイドスクリプト言語を用いて動的に変更するウェブ技術を指す抽象概念。">DHTML</a>で動的にページの一部を書き換えるというアプローチを取る。</p>
                         <p>AjaxはAsynchronous (アシンクロナス/エイシンクロナス、非同期) JavaScript + <span title="XML|Extensible Markup Language (エクステンシブルマークアップランゲージ)。">XML</span>の略で、2005年2月18日にJesse James Garrettにより名付けられた。</p>
                        <cite><a href="http://ja.wikipedia.org/wiki/Ajax"><strong>Ajax</strong> From Wikipedia</a></cite>
                      </dd>
                </dl>
            </blockquote>
<!-- CODE / -->
        </div>
    </body>
</html>

How to create a plugin for jQuery

unknown

How to create a plugin for jQuery

input要素にフォーカスが当たった時にハイライト表示するjQueryプラグインを作成する方法が掲載されています。

jquery.inputHighlight.js
(function($){
    $.inputHighlight=function(color){
        /* input要素に繰り返し処理 */
        $("input").each(function(){
            /* フォーカスが当たったときに背景色を変更 */
            $(this).focus(function(){
                $(this).css({"background-color":color});
            });
            /* フォーカスが外れた時に背景色を白にする */
            $(this).blur(function(){
                $(this).css({"background":"#fff"});
            });
        });
    }
})(jQuery);
設置サンプルサンプルを見る
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta http-equiv="Content-Language" content="ja" />
        <meta http-equiv="Content-Script-Type" content="text/javascript" />
        <meta http-equiv="Content-Style-Type" content="text/css" />
        <meta http-equiv="imagetoolbar" content="no" />
        <title>設置サンプル</title>
        <link rel="stylesheet" href="/content/lib/global.css" type="text/css" />
        <!-- JS -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
        <script type="text/javascript" src="include/ajax/jquery_plugin/jquery.inputHighlight.js"></script>
        <script type="text/javascript">
            $(function(){
                $.inputHighlight("#a6cdec");
            });
        </script>
        <!-- CSS -->
        <style type="text/css">
            input { padding:2px; border:1px solid #ccc; background:#fff; }
            label { width:7em; float:left; }
        </style>
    </head>
    <body>
        <div id="wrap">
            <p>参照:<a href='http://yensdesign.com/2008/12/how-to-create-a-plugin-for-jquery/'>How to create a plugin for jQuery</a></p>
<!-- CODE -->
            <form method="post" action="#" name="test">
                <p><label for="name">Name</label><input id="name" type="text" /></p>
                <p><label for="country">Country</label><input id="country" type="text" /></p>
                <p><label for="password">Password</label><input id="password" type="password" /></p>
            </form>
<!-- CODE / -->
        </div>
    </body>
</html>

関連コンテンツ

Q. このサイトの情報はお役に立ちましたでしょうか?

投票する 投票結果を見る

管理人に【web拍手】を送るweb拍手(1行メッセージも送れます♪)

pagetop

polarized women