본문 바로가기
✏️ 공부/JavaScript

비밀번호 보이기/감추기 기능

by minzyee 2022. 4. 16.

* 공부 및 자격증을 위해 작성하는 글입니다.

* 부족한 내용이나 틀린 내용을 알려주시면 감사합니다.

* 코딩애플 js 강의를 참고하여 기능을 연습했습니다.


 

 

공부한 것: 

조건문으로 클릭 횟수의 홀짝 횟수를 변수에 받아서

다크모드/라이트모드 전환하는 것을 배웠고

그것을 조금 응용해서 비밀번호 보이기/감추기 기능을 연습해봤다.

 

비밀번호를 입력한 뒤 'show' 버튼을 누르면

암호로 되어있던 문자가 읽을 수 있는 문자로 바뀐다.

(그리고 로그인 하면 비밀의 공간으로 이동함)

 

 

 

로그인

 

 


 

 

코드
<!-- css -->
<style>
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    form {
        margin: 0 auto;
        padding: 20px;
        width: 300px;
        height: 300px;
        border: 1px solid #ddd;
        border-radius: 14px;
        background-color: #fff;
    }

    #login_wrap {
        margin: 0 auto;
        width: 100%;
        height: 100%;
        text-align: center;
    }

    h2 {
        font-weight: normal;
        margin: 0 auto 20px;
    }

    input {
        width: 240px;
        height: 40px;
        border: 1px solid #ddd;
        border-radius: 4px;
        text-indent: 10px;
        margin-bottom: 10px;
    }

    #pw_wrap {
    	position: relative;
    }

    #show_pw {
        position: absolute;
        right: 20px;
        top: 6px;
        padding: 2px;
        cursor: pointer;
        border: 1px solid #ddd;
        border-radius: 8px;
        background-color: #eee;
    }

    #login_btn {
        width: 240px;
        height: 40px;
        margin-top: 10px;
        border: 1px solid #ddd;
        border-radius: 8px;
        color: #fff;
        background-color: #007bff;
        transition: all 0.15s;
        cursor: pointer;
    }

    #login_btn:hover {
    	background-color: #0062cc;
    }
</style>
    
    
<!-- html -->
<form action="">
    <div id="login_wrap">
        <h2>로그인</h2>
        <input type="text" id="email" placeholder="아이디를 입력하세요.">
        <div id="pw_wrap">
            <input type="password" id="pw" placeholder="비밀번호를 입력하세요.">
            <button type="button" id="show_pw">show</button>
        </div>
        <button type="submit" id="login_btn">로그인</button>
    </div>
</form>


<!-- script --> 
<script>
    var pwCount = 0;

    document.querySelector('#show_pw').addEventListener('click', function(e){
	e.preventDefault();

        pwCount++; //버튼 누를 때마다 클릭 횟수 +1
        console.log(pwCount);

        if(pwCount % 2 === 1){
        	document.querySelector('#pw').setAttribute('type', 'text');
        }

        else {
        	document.querySelector('#pw').setAttribute('type', 'password');
        }
    });
</script>

 


 

제이쿼리로 쓰면 훨씬 간단해짐

// 제이쿼리로 썼을 때
<script>
    var pwCount = 0;

    $('#show_pw').on('click', function(e){
        e.preventDefault();

        pwCount++; //버튼 누를 때마다 클릭 횟수 +1

        if(pwCount % 2 === 1){
            $('#pw').attr('type', 'text');
        }

        else {
            $('#pw').attr('type', 'password');
        }
    });
</script>

 

 

 

console.log(pwCount) 했을 때

반응형