- 나름 생각해서 여백의 미를 강조 ??
(음? ..)해 사이트를 만들어보았지만..intro가 너무 밋밋했기에 위와 같은 효과를 넣어봤다. 전에 유튜버 수코딩님이 올려주신 간단한 예제들을 풀어보다가 굉장히 인상적인 파트가 있었기에 참고하여 구현을 해보았다.
'use strict'; // const intro = document.querySelector('.intro-title'); const infor = document.querySelector('.information-title'); const favor = document.querySelector('.favorite-title'); const inwecode = document.querySelector('.inwecode-title'); //
// function blink() { intro.classList.toggle('active'); infor.classList.toggle('active'); favor.classList.toggle('active'); inwecode.classList.toggle('active'); } // setInterval(blink, 500);⬇// 중복 요소들을 줄이고자 선택 요소들 및 toggle 메소드를 한 객체에 묶음 const blinkObject = { list: [intro, infor, favor, inwecode], addActiveClass: function () { for (const item of this.list) { // this.list: list array를 가리킨다. item.classList.toggle('active'); // } }, }; // // function blink() { blinkObject.addActiveClass(); } // setInterval(blink, 500);
classList.toggle() 메소드를 사용하였다. (소괄호 안 클래스가 없을 시 추가, 있을 시 삭제, MDN 참고)
active 클래스가 있을 때와 없을 때의 CSS 스타일링을 모두 한 후 setInterval을 통해 0.5초 간격으로 지속 실행되는 코드를 작성하였다.
(cursor는 CSS의 Pseudo-elements로 작성, active가 있을 때는 커서 나타남, active 클래스가 없을 시 클래스 사라짐)
기존에는 blink() 안 intro.classList.toggle('active') 처럼 toggle을 적용한 요소들을 일일이 나열했지만, 중복을 줄여보고자 위처럼 array, object 및 for..of 을 사용하여 리팩토링을 해보았다.
물론 전자가 코드 줄은 짧고 간단하지만, 중복 제거를 연습해보고자 한다는 것에 의의를 두고 작업했다.
'use strict'; // const intro = document.querySelector('.intro-title'); // // 문장 및 글자로 분할하는 함수 function introRandomArr() { const stringArr = ["hello, I'm yongmin!!", "hello, I'm 20th wecoder!!"]; const selectString = stringArr[Math.floor(Math.random() * stringArr.length)]; const selectStringToArr = selectString.split(''); return selectStringToArr; } // // resetTyping function resetTyping() { intro.textContent = ''; print(introRandomArr()); } // // typing text function print(randomArr) { if (randomArr.length > 0) { intro.textContent = intro.textContent + randomArr.shift(); setTimeout(() => print(randomArr), 80); } else { setTimeout(() => resetTyping(), 3000); } } // print(introRandomArr());
Math.floor()(소수점 내림), Math.random()(0~1사이 랜덤 숫자 출력), String.prototype.split()을 통해 배열 안의 문장을 무작위로 선택 후 글자들을 분할 및 배열로 리턴하였다.
Math.floor(Math.random() * stringArr.length) 부분에서 소숫점, 랜덤, 배열 길이를 응용한 것이 매우 인상적이었다. (수학적인 요소가 들어가니 좀 신기하기도 했다!!!)
textContent = ''을 통해 출력된 글자들을 없애는 기능을 구현했다.
innerText로도 사용이 가능했지만, 좀더 자유도가 높은 textContent를 선택했다.
introRandomArr의 최종 리턴값인 selectStringToArr(분할된 글자 배열)을 인자로 전달하여 한글자씩 출력이 되도록 하였다.
shift()를 통해 맨 앞글자부터 하나씩 빼내어 intro.textContent에 추가하였다.
selectStringToArr의 글자들이 모두 빠져나가 length값이 0이 되면 resetTyping 함수를 실행시켰다.(이해하기 가장 어려웠던 부분이었다.... 😢😢😢)
- 최근 브라우저 및 휴대폰 모두 다크모드를 사용하다보니 눈에 피로감이 덜해졌다. 또한 구글, 네이버 등 많은 웹에서 지원을 한다. 때문에 직접 해보고자 작업을 하였다.
<!-- html button 태그--!> <button type = "button" class="handler" data-value="Bright">Dark</button>// Javascript 'use strict'; const handlerButton = document.querySelector('.handler'); // handlerButton.addEventListener('click', function () { if (handlerButton.dataset.value === 'Bright') { handlerButton.textContent = 'Bright'; handlerButton.dataset.value = 'Dark'; } else { handlerButton.textContent = 'Dark'; handlerButton.dataset.value = 'Bright'; } });
addEventListener('click', ~~)와 data attribute를 통해 적용하였다.
(MDN 데이터속성, JavaScript30 chapter1(Drum kit)참고)
if 문을 통해서 html의 요소가 해당하는 data attribute값을 갖고 있는 경우, JavaScript의 dataset을 통해 접근하여 data-값을 변경하고 textContent를 통해 button 태그의 text를 변경할 수 있었다.
'use strict'; // const header = document.querySelector('.header'); const introPage = document.querySelector('.intro'); const informationPage = document.querySelector('.information'); const favoritePage = document.querySelector('.favorite'); const inwecodePage = document.querySelector('.inwecode'); const items = [header, introPage, informationPage, favoritePage, inwecodePage]; // // dark Class 추가 함수 function addDarkClass(parameter) { parameter.forEach((item) => item.classList.toggle('dark')); } // // 클릭시 dark class를 추가하는 함수 실행 handlerButton.addEventListener('click', function () { addDarkClass(items); });
classList.toggle() 메소드를 사용하였다. (소괄호 안 클래스 없을 시 추가, 있을 시 삭제)
dark 클래스가 있을 때와 없을 때의 CSS 스타일링을 모두 한 후 이벤트 리스너를 통해 dark 클래스를 추가하는 코드를 작업했다.
(dark 클래스가 있을 때는 dark mode 스타일링 적용, active 클래스가 없을 시 기존 스타일 적용)
기존에는 for..of를 통해 items를 순환하면서 toggle 메소드를 통한 dark를 추가했지만, forEach를 사용하니 훨씬!!!! 간결해졌다. (조금씩 응용하는 맛이 생기는 것 같다 ~)
커서 깜빡임 코드와 거의 비슷하다. (toggle을 통한 클래스 추가 및 제거이이므로 ..)
자기소개 페이지 JS파일을 작성하면서 중복의 최소화에 대한 고민이 생각의 폭을 넓히는데 가장 좋았던 것 같다. 단순히 나열식보다는 '어떻게 하면 간결하게 작성할 수 있을까' '가독성을 어떻게 좋게 할까' 등의 생각들을 하면서 얕은 지식으로 뭔가 해보려고 노력했다는 것에 의의를 두고 싶다.
크으으👍🏻👍🏻