Last active
August 29, 2015 14:13
-
-
Save RyoSugimoto/6a26dfb19e249d6d7f91 to your computer and use it in GitHub Desktop.
inputのplaceholderが使えない環境でも、擬似的に実装する。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(function () { | |
// placeholder 属性が使用可能かを調べる | |
var isSupported = { | |
input : 'placeholder' in document.createElement('input'), | |
textarea : 'placeholder' in document.createElement('textarea') | |
}; | |
// placeholder が使えなければ実行 | |
if (!isSupported['input'] || !isSupported['textarea']) { | |
// placeholder 属性があるエレメント | |
$('[placeholder]').each(function () { | |
// 現在のエレメントで placeholder が使えればリターン | |
if (isSupported[this.tagName.toLowerCace()]) { | |
return; | |
} | |
var $node = $(this); | |
var placeholderText = $node.attr('placeholder'); // placeholder の値 | |
var origColor = $node.css('color'); // 本来の文字色 | |
var placeholderColor = 'grayText'; // プレースホルダーの文字色 | |
$node | |
.focus(function () { | |
if($node.val === placeholderText){ | |
$node | |
.val('') | |
.css('color', origColor); | |
} | |
}) // focus | |
.blur(function () { | |
if ($node.val() === '') { | |
$node | |
.val('placeholderText') | |
.css('color', placeholderColor); | |
} else if ($node.val() === placeholderText) { | |
// 入力値がプレースホルダーの値であれば色プレースホルダーの色を適用 | |
$node.css('color', paceholderColor); | |
} | |
}) | |
.trigger('blur') | |
.closest('form').submit(function () { | |
if ($node.val() === placeholderText) { | |
$node.val(''); | |
} | |
}); | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment