소프트웨어/JavaScript

[JavaScript] 함수 활용한 refactoring - 야간 모드 예제 간결하게

정보통신 고심이 2023. 2. 2. 16:19

오늘은 함수를 이용하여 야간모드 버튼을 간결하게 바꾸는 작업을 배웠다. 

지금은 night / day 버튼을 사용하는 간단한 예제를 만들었지만

나중에 다양한 용도를 추가하기 위해 함수를 활용하고 코드가 더 길어진다면 최대한 반복을 줄인 효율적인 코드가 필요하다.  

 

 

이전 포스팅에서 사용한 예제의 일부분이다. 

    <body>
        <h1><a href="index.html">WEB</a></h1>
        <input id ="night_day" type="button" value="night" onclick="
        var target = document.querySelector('body');
        if (this.value ==='night'){
            target.style.backgroundColor='black';
            target.style.color='white';
            this.value ='day';

            var alist = document.querySelectorAll('a');
            var i = 0;
            while(i<alist.length){
                alist[i].style.color='powderblue';
                i = i+1;
        }

        }   
            else {
            target.style.backgroundColor='white';
            target.style.color='black';
            this.value ='night';

            var alist = document.querySelectorAll('a');
            var i = 0;
            while(i<alist.length){
                alist[i].style.color='blue';
                i = i+1;
        }
        }
        ">
  	</body>

지금은 야간모드 전환 버튼이 한개지만 버튼이 여러개가 될 경우에는 수정이 번거로워진다.

따라서 <input> 부분의 반복을 줄이기 위해 nightDayHandler() 함수를 만들고 <input> 버튼에 자바스크립트 코드를 넣을 것이다.

 

 

1. nightDayHandler() 함수 만들기 

        <script>
            function nightDayHandler(self){
                var target = document.querySelector('body');
                if (self.value ==='night'){
                    target.style.backgroundColor='black';
                    target.style.color='white';
                    self.value ='day';

                    var alist = document.querySelectorAll('a');
                    var i = 0;
                    while(i<alist.length){
                        alist[i].style.color='powderblue';
                        i = i+1;
                    }
                }   
                else { 
                    target.style.backgroundColor='white';
                    target.style.color='black';
                    self.value ='night';

                    var alist = document.querySelectorAll('a');
                    var i = 0;
                    while(i<alist.length){
                        alist[i].style.color='blue';
                        i = i+1;
                    }
                } 
            }      
        </script>

<script> 태그를 추가하여 <input> 버튼의 자바스크립트 코드를 넣는다.

 

주의) onclick 이벤트 안에서 this는 더이상 이벤트가 소속된 태그를 가리키지 않기에 self값을 넣어야한다. 

function nightDayHandler(this) X

function nightDayHandler(self) O

 

 

 

2. onclick 속성값으로 nightDayHandler() 지정 

    <body>
        <h1><a href="index.html">WEB</a></h1>
        <input id ="night_day" type="button" value="night" onclick="
            nightDayHandler(this);
        ">
    </body>

주의) this 인자를 self 매개변수로 받아야한다 

nightDayHandler(this);

 

 

함수를 이용하면 수정도 편하고 코드도 훨씬 간결해진다. 또한 함수의 이름을 통해 어떤 기능을 하는지도 알 수 있다.