Skip to content

Instantly share code, notes, and snippets.

@nissuk
Created February 3, 2011 16:06
Show Gist options
  • Save nissuk/809685 to your computer and use it in GitHub Desktop.
Save nissuk/809685 to your computer and use it in GitHub Desktop.
HTML5のplaceholderのフォールバック用jQueryプラグイン
/**
* jQuery placeholder fallback plugin (public domain)
*
* HTML5のplaceholderを実装していないブラウザでplaceholderの動作を模倣します。
* .val()で値を設定するのを避け、<label>を生成して<input>/<textarea>上に被せます。
*
*
* 使用例:
* $(function(){
* $('input, textarea').placeholder();
* };
*
*/
(function($){
$.fn.placeholder = function(){
// Opera 11が<textarea>のplaceholderを実装していないようなので、placeholderを実装しているかを
// <input>と<textarea>で別個に確認します。
var browser_support = {
input: 'placeholder' in $('<input>')[0],
textarea: 'placeholder' in $('<textarea>')[0]
};
return this.each(function(){
var $this = $(this);
var text = $this.attr('placeholder');
if (browser_support[this.tagName.toLowerCase()] || !text) return;
var label = $('<label>');
label
.css({
cursor: 'text',
width: $this.width(),
position: 'absolute',
overflow: 'hidden',
color: '#aaa',
fontSize: $this.css('fontSize'),
fontFamily: $this.css('fontFamily'),
whiteSpace: 'nowrap'
})
.text(text);
var id = $this.attr('id');
// ラベル上をクリックしたときに該当<input>/<textarea>にフォーカスできるようにします。
id ? label.attr('for', id) : label.click(function(){ $this.focus() });
$this.after(label);
// placeholderテキストの位置を設定します。
// ブラウザによってキャレット初期位置が違うのでそれに合わせて位置を変えたほうがいいかもしれません。
// (参考:
// IE 6-8: <input>/<textarea>共にキャレット初期位置が左上
// Firefox 3.6: <input>のキャレット初期位置が左中央、<textarea>のキャレット初期位置が左上
// Opera 11: <textarea>のキャレット初期位置が左上)
var offset = $this.offset();
offset.top += parseFloat($this.css('borderTopWidth'));
offset.left += parseFloat($this.css('borderLeftWidth'));
// IEの後方互換モードはinputのpaddingを反映しないようなので、
// IEの後方互換モード以外の時だけplaceholderテキストの位置にpadding分を加算します。
if ($.support.boxModel) {
offset.top += parseFloat($this.css('paddingTop'));
offset.left += parseFloat($this.css('paddingLeft'));
}
label.offset(offset);
$this
.focus(function(){ label.hide() })
.blur(function(){ if ($this.val() == '') label.show() });
// valueに初期値が入っている場合、placeholderテキストを予め非表示にします。
if ($this.val() != '') label.hide();
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment