Categories
Javascript + jQuery 개발(Development)

placeholder 미지원 브라우저 대응

낮은 버전의 IE처럼 HTML5에 추가된 placeholder 속성을 지원하지 않는 브라우저가 있다.
그런 경우 javascript를 이용하여 placeholder 속성을 지원하는 것처럼 흉내내는 방법.
focus를 잃었을 때 placeholder 속성의 값을 value로 넣어주고, focus를 얻어주면 빈값을 넣어주는 방식이다.
이 방법의 단점은 Form을 submit 할 때 input 값에 placeholder 속성값이 들어가 있는지 확인을 해주어야 한다는 점이다. (아래 추가된 내용으로 해결)
또 script 내에서 input 값을 빈값으로 변경할 경우(ex. $(“#input1”).val(“”);), 다시 placeholder를 노출시키기 위해서는 blur() 함수를 따로 호출해야 한다.(focus 변화가 없으므로) (아래 추가된 내용으로 해결)
HTML

Javascript

// placeholder를 지원하지 않는 브라우저 대응
function initPlaceholder() {
	if (!("placeholder" in document.createElement("input"))) {	// 지원여부 체크
		var $input_placeholder = $("input[placeholder]");
		$input_placeholder.each(function () {
			var value = $(this).val().trim();
			$(this).focus(function () {
				if ($(this).val().trim() == $(this).attr("placeholder")) {
					$(this).css("color", "");
					$(this).val("");
				}
			}).blur(function () {
				if ($(this).val().trim() == "") {
					$(this).css("color", "#a6a6a6");
					$(this).val($(this).attr("placeholder"));
				} else {
					$(this).css("color", "");
				}
			}).blur();
		});
	}
}

+ 내용 추가
jQuery의 val function을 오버라이딩해주면 값 변경시마다 blur를 호출할 필요가 없다(값을 val 함수로 변경한다는 전제조건 하에서. input1.value = “”; 는 적용 안됨).
+ 내용 추가
val function 오버라이딩 부분 중 getter 부분도 placeholder 값과 비교하여 리턴하도록 변경.
한계점은 $(“#input1”).val(); 시에는 원하는대로 동작하지만 document.getElementById(“input1”).value 처럼 접근할 때에는 placeholder 값이 나온다는 것.
기존에는 focus 함수에서 placeholder 값과 비교했는데, val() getter를 오버라이드 했기 때문에 “” 와 비교하는 점에 주의.

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);
	}
}

Gist Github에서 update 시키고 있다.