Skip to content

Instantly share code, notes, and snippets.

@bulnak

bulnak/initPlaceholder.js

Last active Oct 12, 2015
Embed
What would you like to do?
support placeholder tag for unsupporting browser with jQuery val function overriding
function initPlaceholder() {
if (!("placeholder" in document.createElement("input"))) { // Browser 지원여부 체크
var $input_placeholder = $("input[placeholder]");
$input_placeholder.each(function () {
$(this).focus(function () {
if ($(this).val().trim() == "") {
$(this).css("color", "").val("");
}
}).blur(function () {
if ($(this).val().trim() == "") {
$(this).css("color", "#a6a6a6").val($(this).attr("placeholder"));
} else {
$(this).css("color", "");
}
}).blur();
});
// jQuery val function overriding for placeholder
(function ($) {
var org_val = $.fn.val;
$.fn.val = function (value) {
var placeholder = $(this).attr("placeholder");
if (typeof value != "undefined") { // setter
if ((value == "" || value == placeholder) && $(this).is("input[placeholder]:not(:focus)")) {
$(this).css("color", "#a6a6a6");
value = placeholder;
} else {
$(this).css("color", "");
}
return org_val.call(this, value);
}
else { // getter
if( this[0].value == placeholder ) {
this[0].value = "";
}
return org_val.call(this);
}
};
})(jQuery);
}
}
// initPlaceholder(); 호출 필요
@bulnak

This comment has been minimized.

Copy link
Owner Author

@bulnak bulnak commented Nov 16, 2012

document 객체를 직접 건드리는 경우에는 한계가 있음.

$("#input1").val(""); // display well
document.getElementById('input1').value = ""; // placeholder text doesn't display

var text = $("#input1").val(); // returns ""
var text = document.getElementById('input1').value; // returns text of placeholder attribute

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment