자바스크립트 과제

yejin·2021년 3월 10일
0
post-thumbnail

마우스 효과

내 답

// <⚠️ DONT DELETE THIS ⚠️>
import "./styles.css";
const colors = ["#1abc9c", "#3498db", "#9b59b6", "#f39c12", "#e74c3c"];
// <⚠️ /DONT DELETE THIS ⚠️>

/*
✅ The text of the title should change when the mouse is on top of it.
마우스가 위에 있을 때 제목 텍스트가 변경되어야 합니다.
✅ The text of the title should change when the mouse is leaves it.
마우스가 나갈 때 제목 텍스트가 변경되어야 합니다.
✅ When the window is resized the title should change.
창의 크기가 조정되면 제목이 변경됩니다.
✅ On right click the title should also change.
마우스 오른쪽 버튼을 클릭하면 제목도 변경됩니다.
✅ The colors of the title should come from a color from the colors array.
제목의 색상은 색상 배열의 색상에서 와야 합니다.
✅ DO NOT CHANGE .css, or .html files.
.css 또는 .html 파일은 변경하지 마십시오.
✅ ALL function handlers should be INSIDE of "superEventHandler"
모든 기능 처리기는 "superEventHandler"의 내부에 있어야 합니다.
*/

const title = document.querySelector("h2");

const superEventHandler = {
  mouseTop: function () {
    title.innerHTML = "mouse is here";
    title.style.color = colors[0];
  },

  mouseOut: function () {
    title.innerHTML = "mouse is gone";
    title.style.color = colors[1];
  },

  resize: function () {
    title.innerHTML = "you just resized";
    title.style.color = colors[2];
  },

  click: function () {
    title.innerHTML = "that was a right click";
    title.style.color = colors[3];
  }
};

title.addEventListener("mouseenter", superEventHandler.mouseTop);
title.addEventListener("mouseout", superEventHandler.mouseOut);
window.addEventListener("resize", superEventHandler.resize);
window.addEventListener("auxclick", superEventHandler.click);

정답

const h2 = document.querySelector("h2");
const colors = ["#1abc9c", "#3498db", "#9b59b6", "#f39c12", "#e74c3c"];

const superEventHandler = {
  handleEnter: function() {
    h2.innerText = "The mouse is here!";
    h2.style.color = colors[0];
  },
  handleLeave: function() {
    h2.innerText = "The mouse is gone!";
    h2.style.color = colors[1];
  },
  handleResize: function() {
    h2.innerText = "You just resized!";
    h2.style.color = colors[2];
  },
  handleSelect: function() {
    h2.innerText = "You're selecting me!";
    h2.style.color = colors[3];
  },
  handleContext: function() {
    h2.innerHTML = "That was a right click!";
    h2.style.color = colors[4];
  }
};

h2.addEventListener("mouseenter", superEventHandler.handleEnter);
h2.addEventListener("mouseleave", superEventHandler.handleLeave);
window.addEventListener("resize", superEventHandler.handleResize);
window.addEventListener("contextmenu", superEventHandler.handleContext);

화면 크기에 따라 배경 색 바뀌게하기

내 답

css

body {
  font-family: sans-serif;
}

.one {
  background-color: darksalmon;
}

.two {
  background-color: pink;
}

.three {
  background-color: olive;
}

javascript

// <⚠️ DONT DELETE THIS ⚠️>
import "./styles.css";
// <⚠️ /DONT DELETE THIS ⚠️>

const body = document.querySelector("body");
const WIDTH_CLASS = ["one", "two", "three"];

function handleResize() {
  let width = window.innerWidth;
  if (width >= 600) {
    body.className = WIDTH_CLASS[0];
  } else if (width >= 300 && width < 600) {
    body.className = WIDTH_CLASS[1];
  } else {
    body.className = WIDTH_CLASS[2];
  }
}

function init() {
  window.addEventListener("resize", handleResize);
}

init();

현재 내 답(2021.06.03)

no css.

javascript

// <⚠️ DONT DELETE THIS ⚠️>
import "./styles.css";
// <⚠️ /DONT DELETE THIS ⚠️>

const body = document.querySelector("body");
const colors = ["#3498db", "#9b59b6", "#f39c12"];

function handleWidth() {
  const width = window.innerWidth;
  if (width > 800) {
    body.style.backgroundColor = colors[0];
  } else if (width < 800 && width > 600) {
    body.style.backgroundColor = colors[1];
  } else {
    body.style.backgroundColor = colors[2];
  }
}

window.addEventListener("resize", handleWidth);

정답

html

<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
  </head>

  <body class="mediumScreen">
    <h2>Hello!</h2>

    <script src="src/index.js"></script>
  </body>
</html>

css

body {
  font-family: sans-serif;
  display: flex;
}

h2 {
  color: white;
}

.bigScreen {
  background-color: #f1c40f;
}

.mediumScreen {
  background-color: #9b59b6;
}

.smallScreen {
  background-color: #3498db;
}

javascript

import "./styles.css";

const body = document.body;

const BIG_SCREEN = "bigScreen";
const MEDIUM_SCREEN = "mediumScreen";
const SMALL_SCREEN = "smallScreen";

function handleResize() {
  const width = window.innerWidth;
  if (width > 1000) {
    body.classList.add(BIG_SCREEN);
    body.classList.remove(MEDIUM_SCREEN);
  } else if (width <= 1140 && width >= 700) {
    body.classList.add(MEDIUM_SCREEN);
    body.classList.remove(BIG_SCREEN, SMALL_SCREEN);
  } else {
    body.classList.remove(MEDIUM_SCREEN);
    body.classList.add(SMALL_SCREEN);
  }
}

window.addEventListener("resize", handleResize);

크리스마스 이브 카운트 다운

정답

html

<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
  </head>
  <body>
    <h1>Time Until Christmas Eve</h1>
    <h2 class="js-clock"></h2>
    <script src="src/index.js"></script>
  </body>
</html>

javascript

import "./styles.css";

const clockTitle = document.querySelector(".js-clock");

function getTime() {
  const xmasDay = new Date(`${new Date().getFullYear()}-12-24:00:00:00+0900`);
  const now = new Date();
  // This is in milisecondsx
  const difference = new Date(xmasDay - now);
  const secondsInMs = Math.floor(difference / 1000);
  const minutesInMs = Math.floor(secondsInMs / 60);
  const hoursInMs = Math.floor(minutesInMs / 60);
  const days = Math.floor(hoursInMs / 24);
  const seconds = secondsInMs % 60;
  const minutes = minutesInMs % 60;
  const hours = hoursInMs % 24;
  const daysStr = `${days < 10 ? `0${days}` : days}d`;
  const hoursStr = `${hours < 10 ? `0${hours}` : hours}h`;
  const minutesStr = `${minutes < 10 ? `0${minutes}` : minutes}m `;
  const secondsStr = `${seconds < 10 ? `0${seconds}` : seconds}s`;
  clockTitle.innerHTML = `${daysStr} ${hoursStr} ${minutesStr} ${secondsStr}`;
}

function init() {
  getTime();
  setInterval(getTime, 1000);
}
init();

나라선택 (초기화x 값 저장되게)

내가 참고했던 코드

html

<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
  </head>
  <body>
    <h1>Where are you from?</h1>
    <select class="country">
      <option value="">--- Choose Your Country ---</option>
      <option value="KR">Korea</option>
      <option value="GR">Greece</option>
      <option value="TR">Turkey</option>
      <option value="FN">Finland</option>
    </select>
    <script src="src/index.js"></script>
  </body>
</html>

javascript


const selectElement = document.querySelector(".country");

function saveCountry(text) {
  localStorage.setItem("country", text);
}

function handleChange(event) {
  const cuurentValue = selectElement.value;
  saveCountry(cuurentValue);
}

if (localStorage.country != null) {
  selectElement.value = localStorage.country;
}

selectElement.addEventListener("change", handleChange);

내 답

html

<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
  </head>
  <body>
    <h1>Where are you from?</h1>
    <select class="country">
      <option value="">--- Choose Your Country ---</option>
      <option value="ko">Korea</option>
      <option value="gr">Greece</option>
      <option value="tu">Turkey</option>
      <option value="fi">Finland</option>
    </select>
    <script src="src/index.js"></script>
  </body>
</html>

javascript

// <⚠️ DONT DELETE THIS ⚠️>
import "./styles.css";
// <⚠️ /DONT DELETE THIS ⚠️>

const loadCountry = document.querySelector(".country");

function save(text) {
  localStorage.setItem("country", text);
}

function handleChange(event) {
  const Value = loadCountry.value;
  save(Value);
}

function loadName() {
  if (localStorage.country == null) {
  } else {
    loadCountry.value = localStorage.country;
  }
}

function init() {
  loadName();
  loadCountry.addEventListener("change", handleChange);
}

init();

정답

html

<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
  </head>
  <body>
    <h1>Where are you from?</h1>
    <select class="js-select">
      <option value="NONE">--- Choose Your Country ---</option>
      <option value="KR">Korea</option>
      <option value="GR">Greece</option>
      <option value="TR">Turkey</option>
      <option value="FI">Finland</option>
    </select>
    <script src="src/index.js"></script>
  </body>
</html>

javascript

import "./styles.css";

const select = document.querySelector(".js-select");

function handleChange() {
  const selected = select.value;
  localStorage.setItem("country", selected);
}

function loadCountries() {
  const selected = localStorage.getItem("country");
  if (selected) {
    const option = document.querySelector(`option[value="${selected}"]`);
    option.selected = true;
  }
}

loadCountries();
select.addEventListener("change", handleChange);

todolist

https://codesandbox.io/s/day-eight-nine-solution-8817f?file=/src/index.js

html

<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
  </head>

  <body>
    <h1>Tasks</h1>

    <form id="js-form">
      <input type="text" placeholder="Add task" />
    </form>

    <div>
      <h3>Pending</h3>
      <ul id="js-pending"></ul>
    </div>

    <div>
      <h3>Finished</h3>
      <ul id="js-finished"></ul>
    </div>

    <script src="src/index.js"></script>
  </body>
</html>

no css

javascript

import "./styles.css";

const pendingList = document.getElementById("js-pending"),
  finishedList = document.getElementById("js-finished"),
  form = document.getElementById("js-form"),
  input = form.querySelector("input");

const PENDING = "PENDING";
const FINISHED = "FINISHED";

let pendingTasks, finishedTasks;

function getTaskObject(text) {
  return {
    id: String(Date.now()),
    text
  };
}

function savePendingTask(task) {
  pendingTasks.push(task);
}

function findInFinished(taskId) {
  return finishedTasks.find(function(task) {
    return task.id === taskId;
  });
}

function findInPending(taskId) {
  return pendingTasks.find(function(task) {
    return task.id === taskId;
  });
}

function removeFromPending(taskId) {
  pendingTasks = pendingTasks.filter(function(task) {
    return task.id !== taskId;
  });
}

function removeFromFinished(taskId) {
  finishedTasks = finishedTasks.filter(function(task) {
    return task.id !== taskId;
  });
}

function addToFinished(task) {
  finishedTasks.push(task);
}

function addToPending(task) {
  pendingTasks.push(task);
}

function deleteTask(e) {
  const li = e.target.parentNode;
  li.parentNode.removeChild(li);
  removeFromFinished(li.id);
  removeFromPending(li.id);
  saveState();
}

function handleFinishClick(e) {
  const li = e.target.parentNode;
  li.parentNode.removeChild(li);
  const task = findInPending(li.id);
  removeFromPending(li.id);
  addToFinished(task);
  paintFinishedTask(task);
  saveState();
}

function handleBackClick(e) {
  const li = e.target.parentNode;
  li.parentNode.removeChild(li);
  const task = findInFinished(li.id);
  removeFromFinished(li.id);
  addToPending(task);
  paintPendingTask(task);
  saveState();
}

function buildGenericLi(task) {
  const li = document.createElement("li");
  const span = document.createElement("span");
  const deleteBtn = document.createElement("button");
  span.innerText = task.text;
  deleteBtn.innerText = "❌";
  deleteBtn.addEventListener("click", deleteTask);
  li.append(span, deleteBtn);
  li.id = task.id;
  return li;
}

function paintPendingTask(task) {
  const genericLi = buildGenericLi(task);
  const completeBtn = document.createElement("button");
  completeBtn.innerText = "✅";
  completeBtn.addEventListener("click", handleFinishClick);
  genericLi.append(completeBtn);
  pendingList.append(genericLi);
}

function paintFinishedTask(task) {
  const genericLi = buildGenericLi(task);
  const backBtn = document.createElement("button");
  backBtn.innerText = "⏪";
  backBtn.addEventListener("click", handleBackClick);
  genericLi.append(backBtn);
  finishedList.append(genericLi);
}

function saveState() {
  localStorage.setItem(PENDING, JSON.stringify(pendingTasks));
  localStorage.setItem(FINISHED, JSON.stringify(finishedTasks));
}

function loadState() {
  pendingTasks = JSON.parse(localStorage.getItem(PENDING)) || [];
  finishedTasks = JSON.parse(localStorage.getItem(FINISHED)) || [];
}

function restoreState() {
  pendingTasks.forEach(function(task) {
    paintPendingTask(task);
  });
  finishedTasks.forEach(function(task) {
    paintFinishedTask(task);
  });
}

function handleFormSubmit(e) {
  e.preventDefault();
  const taskObj = getTaskObject(input.value);
  input.value = "";
  paintPendingTask(taskObj);
  savePendingTask(taskObj);
  saveState();
}

function init() {
  form.addEventListener("submit", handleFormSubmit);
  loadState();
  restoreState();
}
init();

랜덤숫자게임

https://codesandbox.io/s/day-ten-solution-fnylk?file=/index.html:0-870

html

<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
  </head>

  <body>
    <h1>Random Number Game</h1>
    <div>
      <h3 class="js-title">Generate a number between 0 and <span>10</span></h3>
      <datalist id="number">
        <option value="50"></option>
        <option value="100"></option>
        <option value="150"></option>
        <option value="200"></option>
      </datalist>
      <input
        list="number"
        id="js-range"
        type="range"
        min="5"
        max="200"
        value="5"
        step="5"
      />
    </div>
    <form id="js-guess">
      <label>Guess the number:</label>
      <input type="number" max="200" min="5" />
      <button>Play!</button>
    </form>
    <div id="js-result">
      <span></span>
    </div>
    <script src="src/index.js"></script>
  </body>
</html>

javascript

const range = document.getElementById("js-range");
const title = document.querySelector(".js-title");
const guessForm = document.getElementById("js-guess");
const result = document.getElementById("js-result");

function handleRangeChange(e) {
  const selectedRange = title.querySelector("span");
  selectedRange.innerHTML = range.value;
}

function handleGuessSubmit(e) {
  e.preventDefault();
  const guessInput = guessForm.querySelector("input");
  if (guessInput.value === "") {
    return;
  }
  const max = range.value;
  const random = Math.ceil(Math.random() * max);
  const userGuess = parseInt(guessInput.value, 10);
  const resultSpan = result.querySelector("span");
  resultSpan.innerHTML = `
  You chose: ${userGuess},
  the machine chose: ${random}.<br />
  <strong>${userGuess === random ? "You won!" : "You lost!"}</strong>
  `;
}

guessForm.addEventListener("submit", handleGuessSubmit);
range.addEventListener("input", handleRangeChange);
profile
♪(๑ᴖ◡ᴖ๑)♪ 기회는 도전에서부터 시작되는 것

0개의 댓글