1월 둘째주부터 약 삼주간 인프런 강의를 통해 HTML, CSS, Java Script의 기초를 배우고, 바로 배운 것을 적용해보고자 to do list 만들기에 돌입했다. 프론트엔드에 대해 막 배운 걸음마 수준이었기에 구글링과 챗지피티의 도움을 많이 받았다. 다만 의미없는 복붙은 피하고자 해당 문법의 강의&챗지피티를 찾아보며 이해가 되면 코드를 작성했다. 며칠이면 해낼 줄 알았는데 일주일이나 소모됐다..너무 루즈해졌던 같기도 하나 결과물을 보니 너무 뿌듯해서 빨리 다른 프로젝트도 해보고 싶다! 넘어가기 전에 배운 것과 오류가 났던 부분을 정리해보고자 한다.

구현에 앞서 내가 평소에 플래너를 쓰며 원했던 기능들을 떠올리며 다음과 같은 목표를 세웠다.
1. 평소에 과목별 구간이 나눠져 있지 않아서 불편했다 -> 1~4개의 구간 선택 가능
2. 항목 삭제 기능
3. 눈이 편안한 화면
4. 리스트 순서 바꾸기( 이건 클릭->드래그 기능을 생각했던거라 공부를 더 하고 추가해야겠다 )
코드작성
<HTML>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css"/>
<link href="https://hangeul.pstatic.net/hangeul_static/css/maru-buri.css" rel="stylesheet">
<title>DayForMe</title>
</head>
<body>
<div class="overlay"></div>
<div class="container">
<hr>
<h1>To-Do-List</h1>
<hr>
<select id="dropdown">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<div class="section">
<div class="box" id="box1">
</div>
<div class="box" id="box2"></div>
<div class="box" id="box3"></div>
<div class="box" id="box4"></div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
- 배경화면이 너무 밝지 않도록 overlay한 겹을 쌓아 밝기를 조정했다
- body 부분의 section 클래스 내의 box1사이가 비어있는 이유는 원래 사이에 리스트 상자 하나에 구현할 코드를 작성했었기 때문이다. 하지만 html내에서 작성하면 box2,3,4에 중복코드가 생기므로 js로 코드를 옮겨 중복을 방지했다.
JS
boxes.forEach((box) => {
box.innerHTML = `
<input type="text" class="subtitle"/>
<div class="middleofsection">
<input type="text" class="textMe" placeholder="할 일 추가하기"/>
<input type="button" class="addBtn" value="+" />
</div>
<ul class="todolist"></ul>
`;
});
※ 여러 줄 문자열을 작성할 땐 `(백틱)을 이용한다
<CSS>
/* 배경 이미지 */
body {
margin: 0;
padding: 0;
background: url('image.jpg');
background-size: cover;
}
/* 오버레이 효과 */
.overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.4);
z-index: 1;
}
.container {
position: relative;
display: flex;
flex-direction: column;
align-items: center;
top: 40px;
z-index: 2;
}
/* 제목 스타일 */
h1 {
color: white;
margin-bottom: 10px;
font-size: 40px;
font-family: serif;
font-weight: bold;
}
/* hr 스타일 */
hr {
width: 85%;
border: 1px solid white;
margin: 5px;
}
select {
position: relative;
top: 10px;
width: 70px;
height: 30px;
font-size: 15px;
background-color: rgba(161, 158, 158, 0.757);
}
.section {
position: relative;
display: flex;
justify-content: space-around;
align-items: center;
top: 20px;
width: 90%;
height: 485px;
border: 2px solid white;
font-family: 'MaruBuriSemiBold';
}
.box {
width: 300px;
height: 460px;
box-sizing: border-box;
padding: 10px 20px;
background-color: rgba(253, 241, 207, 0.812);
border-radius: 2px;
}
.subtitle {
display: block;
width: 70%;
height: 30px;
margin: auto;
font-family: 'MaruBuri';
font-size: 16px;
font-weight: bold;
text-align: center;
background-color: rgb(247, 229, 175);
border: 1px solid rgba(143, 141, 136, 0.658);
}
.middleofsection {
display: flex;
justify-content: center;
position: relative;
top: 5px;
margin: 5px;
}
.textMe {
border: white;
width: 60%;
color: rgba(31, 31, 31, 0.551);
font-family: 'MaruBuri';
}
.addBtn {
position: relative;
left: 3px;
border: 1px solid rgba(149, 146, 140, 0.658);
cursor: pointer;
border-radius: 4px;
}
.todolist {
list-style-type: none;
padding-left: 0%;
}
구현하기
1) 드롭다운 선택에 따라 상자 보이기
JS
const boxes=document.querySelectorAll(".box");
const selectBox=document.getElementById("dropdown");
먼저 모든 box 요소를 모아 boxes를 통해 가져오고, selectbox를 통해 dropdown의 요소를 불러왔다.
boxes.forEach(function(box){
box.style.display="none";
})
document.addEventListener("change",function(){
let selectedValue=parseInt(selectBox.value)
for(let i=0;i<selectedValue;i++){
boxes[i].style.display="block";
}
})
forEach문으로 첫 화면에서는 모든 상자가 가려지게 하고, change이벤트가 발생하면 for문을 이용하여 드롭다운의 값에 따라 상자가 보이게 했다.
하지만 여기서 문제가 생김!!!!
문제
1. 드롭다운 1을 선택해도 상자 한 개가 안보임(2,3,4개는 보임)
2. 상자 수 2 → 3으로 변경은 되는데, 3 → 2로 변경은 안됨
문제 분석 & 해결방안
1. select의 기본값이 1이라 box.style.display="none";이 적용된 초기화면에서는 1을 선택해도 change이벤트가 발생하지 않음 → 초기 화면에서 기본 선택값(1)에 맞춰 박스를 표시하는 코드 추가 & document 전체가 아니라 select 요소에 구체적으로 이벤트를 걸음
2. for 루프에서 boxes[i].style.display = "block";만 실행함 → 새로운 이벤트가 발생하면 기존 요소들을 다시 display: none;으로 변경하는 과정이 필요함
JS
const boxes=document.querySelectorAll(".box");
const selectBox=document.getElementById("dropdown");
window.addEventListener("DOMContentLoaded", function () {
updateBoxes(parseInt(selectBox.value));
});
selectBox.addEventListener("change",function(){
updateBoxes(parseInt(selectBox.value));
});
function updateBoxes(selectedValue){
boxes.forEach(function(box){
box.style.display="none";
});
for(let i=0;i<selectedValue;i++){
boxes[i].style.display="block";
}
}
이에 따라 수정된 JS 코드이다!
2) 할 일 추가하기
1. input창에 입력 후 enter를 눌렀을 때 와
2. + 버튼을 눌렀을 때 의 두 가지 방법으로 할 일을 추가할 수 있도록 코드를 짰다.
JS
const todoinput=box.querySelector(".textMe");
const todoList=box.querySelector(".todolist");
const addBtn = box.querySelector(".addBtn");
todoinput.addEventListener("keydown",function(event){
if(event.keyCode===13){
addToList();
}
});
addBtn.addEventListener("click", function(){
addToList();
});
addToList() 메소드를 통해 ul에 li를 삽입할 예정이다.
이 때 상자 안의 CSS를 작성하며 강의로는 배우지 못했던 여러 기능들을 접했다
cursor: pointer; /* 마우스를 올리면 손가락 모양으로 변경 */
버튼의 스타일을 변경하면 **클릭 효과(기본 스타일 변화)**가 사라지는데, 그 이유는 브라우저 기본 스타일이 덮어쓰기 되었기 때문이다.
border: gray;를 설정했다가 +버튼의 클릭효과가 사라져서 잠시 당황했었다..
border-radius는 값을 크게 하면 모서리가 더 둥글어지고, 작게 하면 덜 둥글어진다
체크 박스, 글을 추가할 span, 삭제 버튼을 createElement()로 만들어서 li에 append하자! 그리고 li까지 ul에 추가!!
const newLi=document.createElement("li");
const newBtn=document.createElement("button");
const newSpan=document.createElement("span");
const delBtn=document.createElement("button");
delBtn.textContent="x";
newLi.appendChild(newBtn);
newLi.appendChild(newSpan);
newLi.appendChild(delBtn);
todoList.appendChild(newLi);
※ append는 노드(Node)뿐만 아니라 문자열(String)도 추가 가능, appendChild 노드(Node)만 추가할 수 있다. 요소를 추가하는 상황이므로 appendChild를 사용
input에 입력한 텍스트를 span에 넣는 동시에 input에 있는 텍스트를 지워주어 리셋했다
newSpan.textContent=todoinput.value;
todoinput.value='';
여기서 또 문제가 생겼다
공백을 입력해도 리스트에 반영이 되는 것..
그래서 addToList메소드에 if문을 추가했다 공백이 아닐 때만 반영이 되도록
function addToList() {
if (todoinput.value !== '') {
const newLi=document.createElement("li");
const newBtn=document.createElement("button");
const newSpan=document.createElement("span");
const delBtn=document.createElement("button");
delBtn.textContent="x";
newBtn.classList.add("checkbox")
delBtn.classList.add("deleteBtn");
newLi.appendChild(newBtn);
newLi.appendChild(newSpan);
newLi.appendChild(delBtn);
newSpan.textContent=inputElement.value;
todoList.appendChild(newLi);
inputElement.value='';
}
}
newBtn.classList.add("checkbox")
delBtn.classList.add("deleteBtn"); 는 체크박스와 삭제버튼을 꾸미기 위해 class를 지정했다
체크박스 설정과 삭제 기능, 4개 상자에 기능 구현하기는 다음 글에서 !!
'프론트엔드' 카테고리의 다른 글
| [React]React 완벽 마스터: 기초 개념부터 린캔버스 프로젝트까지 ② (0) | 2025.03.31 |
|---|---|
| [React]React 완벽 마스터: 기초 개념부터 린캔버스 프로젝트까지 ① (0) | 2025.03.22 |
| [HTML, CSS] 네이버 클론코딩 ② (0) | 2025.02.18 |
| [HTML, CSS] 네이버 클론코딩 ① (0) | 2025.02.09 |
| [JavaScript] To Do List 만들기 ② (0) | 2025.02.06 |