이때까지 html에서 작성한 내용을 JavaScript로 다루는 방법만 사용했다.
이번에는 JavaScript를 사용해서 작성한 내용을 html로 가져가는 방법을 사용해 보자.
//background.js
const images = ["0.jpg", "1.jpg", "2.jpg"]; //3개의 이미지의 이름을 배열로 만들어 놓은 상태
const chosenImage = images[Math.floor(Math.random()*images.length)];
//배열의 길이만큼만 곱해주는 이유는 random함수는 0에서 1까지의 값만 나오는데, 3을 곱해주게 되면 0에서 3까지의 값만 나오게 된다.
const bgImage = document.createElement("img"); //img태그 생성
bgImage.src = `img/${chosenImage}`; //랜덤 생성된 숫자의 이름을 가진 이미지를 img태그의 src로 설정. 이미지 이름이 0,1,2..와 같은 이름으로 되어있지 않으면 사용할 수 없는 방법
//background.js
//...
document.body.appendChild(bgImage); //제일 마지막 태그로 추가된다.
//가장 위에 추가하고 싶다면 prepend를 사용한다.
사용자가 todo를 입력할 form과, todo를 나열한 list가 필요하다.
<!--index.html-->
<form id = "todo-form">
<input type = "text" placeholder = "Write a To Do and Press Enter" required />
</form>
<ul if="todo-list"></ul>
html에서 input은 submit 될 때 웹페이지가 새로고침 된다.
ToDo List를 생성할 때마다 새로고침 할 필요는 없으므로 새로고침 기능을 막아보자.
//todo.js
const toDoForm = document.getElementById("todo-form"); //html의 form태그
const toDoInput = toDoForm.querySelector("input"); //form태그의 자식태그인 input
const toDoList = document.getElementById("todo-list"); //ul 태그
function handleToDoSubmit(event){ // 방금 발생한 event를 함수의 첫번째 인자로 준다.
event.preventDefault(); //submit의 기본동작인 새로고침이 일어나지 않게 한다.
const newToDo = toDoInput.value; //변수에 input 값을 저장시킨다.
toDoInput.value = ""; //화면에서 입력창을 비워주기 위해 값을 지운다.
}
toDoForm.addEventListener("submit", hadnleToDoSubmit);//form태그에서 submit이 일어나면 handleToDoSubmit 함수를 실행시킨다.