My/Job (개인작업물)

jQuery IE 버전에 Placeholder 적용하기

알찬돌삐 2012. 2. 2. 10:44
이번에 MS 에서 XP 는 IE8 까지, 윈도우 7은 IE9 까지 강제 업데이트를 진행하기로 하였답니다.
웹개발자들에게는 환영할만한 소식입니다.
드디어 개발시 IE6 을 고려하지 않아도 되게 될듯 합니다.ㅠㅠ

서론은 이쯤에서 끝내고, Placeholder 란 뭔가.
 

 
위 화면은 제가 주력으로 사용하는 모포털(daum)의 로그인 화면입니다.
아이디와 비밀번호 입력창에 회색으로 희미하게 적용된 부분이 있습니다.

그렇습니다. Placeholder 는 텍스트 박스에 미리 희미하게 입력되어 있어서 사용자들의 입력을 도와주는 기능을 말합니다. (HTML5 에서 적용되는 input attribute 입니다.)

아래는 HTML5 의 Placeholder 를 지원하는 브라우저입니다. 


 Browsers  Placeholder Support
 IE 9 이하  X
 Firefox 3.7 +  ✓
 Safari 4.0 +  ✓
 Chrome 4.0 +  ✓
 Opera 11  ✓

역시나 진리의 갑 MS.....
지원하지 않는군요.... 

그래서 대부분의 사이트에서 Placeholder 를 사용하기 위해 Javascript 를 사용하는데요.
일반적으로 input 태그에 value 에 값을 넣고 글자색을 희미하게 합니다.
이런 경우 값 체크를 제대로 하지 않으면, Placeholder 라고 넣어둔 값이 Submit 되는 경우가 발생합니다.


그럼, 이를 방지하기 위해 다른 방법을 써보죠.
스타일시트에 아래 코드를 적용합니다.

label.absolute { 
    position: absolute; 
    color:#999; 
    display: none; 
    cursor: text
}
input.focusbox { 
    border:1px solid #23adb2;
}
input:focus { 
    outline: #23adb2 solid thin 
} 

input:focus 는 크롬을 위해서 넣어둡니다. ^^.
포커스시 유저 인터페이스는 동일해야 하므로 맞추는게 낫지요.

아래 자바스크립트 코드를 페이지의 하단에 넣어줍니다.

jQuery(function () {
    if (!("placeholder" in document.createElement("input"))) { 
        jQuery(":input[placeholder]").each(function () {
            var $this = jQuery(this);
            var pos = $this.offset();
            if (!this.id) this.id = "jQueryVirtual_" + this.name;
            if (this.id) {
                if (jQuery.browser.version  < 8) {
                    $this.after("<label for='" + this.id + 
                        
"' id='jQueryVirtual_label_" + this.id + 
                        
"' class='absolute'>" + $this.attr("placeholder") + 
                        
"</label>");
                    $("#jQueryVirtual_label_" + this.id).
                        
css({"left":(pos.left+5), "margin-top":3, 
                       
"width":$this.width()});
                }
                else {
                    $this.after("<label for='" + this.id + 
                   
"' id='jQueryVirtual_label_" + this.id + 
                   
"' style='left:" + (pos.left+5) + 
                    
"px;margin-top:2px' class='absolute'>" + 
                    $this.
attr("placeholder") + "</label>");
                }
            }
        }).focus(function () {
            var $this = jQuery(this);
            $this.addClass("focusbox");
            jQuery("#jQueryVirtual_label_" + $this.attr("id")).hide();
        }).blur(function () {
            var $this = jQuery(this);
            $this.removeClass("focusbox");
            if(!jQuery.trim($this.val())) 
                jQuery
("#jQueryVirtual_label_" + $this.attr("id")).show();
            else jQuery("#jQueryVirtual_label_" + $this.attr("id")).hide();
        }).trigger("blur");
    }
}); 

이렇게 하시면 Placeholder 를 지원하지 않는 브라우저에서 Placeholder 역할을 대체할수 있습니다.

샘플파일을 첨부하니 다운받아서 확인해보세요.





아래 링크에서 바로 확인할 수 있습니다.

http://jsfiddle.net/d9bnV/ 
 

.