14
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

jQueryプラグインを作成してみる

Last updated at Posted at 2014-07-30

jQueryのプラグインの作成手順を共有します。

なぜjQueryのプラグイン

  • コードを明るく書ける
  • 1回だけ書いて、どこでも使える(DRY)

新規のプラグインの定義

myPlugin.jp
(function(){
// 内容
})(jQuery);

functionの定義

myPlugin.jp
$.fn.<function名> = function(userOptions){
...
};

defaultオプションの定義

myPlugin.jp
$.fn.<function名> = function(userOptions){
var options = {
// defaultオプション
}
$.extend(options, userOptions); // オプションがuserOptionsで更新される
...
};

functionのマイン内容

myPlugin.jp
return $(this).each(function(){ // 注:eachを必ず付けてください
...
});

### 例:

myPlugin.jp
$.fn.fade_anime = function(userOptions){
var options = {
  interval: 500,
  opacity: 0.5
}
$.extend(options, userOptions);
return $(this).each(function(){
  var container = $(this);
  var fadeIn = true;
  var timerId = setInterval(function(){
  if (fadeIn){
    container.fadeTo("fast", options.opacity);
    fadeIn = false;
  } else {
    container.fadeTo("fast", 1);
    fadeIn = true;
  }
}, options.interval);
});
}(jQuery);

呼び出すの例

main.js
$("#div1").fade_anime();
$("#div2").fade_anime({interval: 1000, opacity: 0.3});

是非試してください

14
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?