본문 바로가기

BLOG/JavaScript

input 비밀번호 보기/숨기기 (눈모양)

회사 사이트 만들면서 구글 로그인처럼 '눈모양이 있으면 좋겠다' 라는 이야기를 들었다.

 

눈모양은 폰트어썸에서 가져왔다.

https://fontawesome.com/

 

흐음..cdn같이 놓고 싶었는 따로 사이트에 안보이네요... 저는 5.0대 버전을 사용하고 있어요.

다운 받으셨다면 <head>안에 넣어주세요.

<link rel="stylesheet" href="../css/lib/fontawesome/css/all.min.css">

 

 

다운받기 귀찮으시다면 일단 떠돌아 다니는 4.0버전 가지고 합시다.

<link rel="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css">

 

 

<div class="input password">
  <label for="password"class="label password">비밀번호</label>
  <input type="password" id="password" class="form-input" placeholder="비밀번호를 입력해주세요.">
  <div class="eyes">
  	<i class="fas fa-eye"></i>
  </div>
</div>

html 은 이렇습니다.

 

4.0버전대는 i 부분의 클래스를 이렇게 변경 해주세요.

<i class="fa fa-eye fa-lg"></i>

 

 

css는 저는 이렇게 했는데 이쁘게 맞춰서 해주시면 됩니다.

.input {
  position: relative;
}

.input .eyes {
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  margin: auto 2px;
  height: 30px;
  font-size: 22px;
  cursor: pointer;
}

 

 

제이쿼리

$(function(){
  // 눈표시 클릭 시 패스워드 보이기
  $('.eyes').on('click',function(){
    $('.input.password').toggleClass('active');

    if( $('.input.password').hasClass('active') == true ){
    	$(this).find('.fa-eye').attr('class',"fas fa-eye-slash").parents('.input').find('#password').attr('type',"text");
    				// i 클래스                // 텍스트 보이기 i 클래스
    }
    else{
    	$(this).find('.fa-eye-slash').attr('class',"fas fa-eye").parents('.input').find('#password').attr('type','password');
    }
  });
});

주석에 보이는 것처럼 i의 클래스를 변경해주면 됩니다.

 

$(function(){
  // 눈표시 클릭 시 패스워드 보이기
  $('.eyes').on('click',function(){
    $('.input.password').toggleClass('active');

    if( $('.input.password').hasClass('active') == true ){
    	$(this).find('.fa-eye').attr('class',"fa fa-eye-slash fa-lg").parents('.input').find('#password').attr('type',"text");
    				// i 클래스                // 텍스트 보이기 i 클래스
    }
    else{
    	$(this).find('.fa-eye-slash').attr('class',"fa fa-eye fa-lg").parents('.input').find('#password').attr('type','password');
    }
  });
});

4.0버전대 클래스명 변경한 것

 

 

코드를 해석하자면 

눈모양을 클릭하면 부모 태그 .input.password가 active 토글시키고,

active가 활성화가 될 때 자식 input의 타입을 text로 바꿔서 비밀번호 텍스트를 보이게 하는 것입니다.

 

다시한번 눈모양을 클릭하면 text로 변한 input 타입을 다시 password로 바꿔주는 거죠.

 

 

생각보다 간단하지 않나요? ㅎㅎ