momentum clone coding - 완성

진실·2021년 7월 11일
0
post-custom-banner

HTML

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="css/clock.css">
    <link rel="stylesheet" href="css/greeting.css">
    <link rel="stylesheet" href="css/todo.css">
    <link rel="stylesheet" type="text/css" href="css/weather.css">
    <title>
      Momentum Clone Coding
    </title>
    <!--<body style="background-image:radial-gradient(rgba(58, 57, 57, 0.1), 
      rgba(0, 0, 0, 0.3)), url('imgs/img26.jpeg'); background-size : cover;">-->
    <body>
      <div class = "weather">
        <div id = "weather_icon"></div>
        <div id = "temperature"></div>
        <div id = "city_name"></div>
      </div>
      <div class = "clock">
        <b class = "time"></b>
      </div>
      <div class = "greeting">
        <b></b>
      </div>
      <div class = "todo_list">
        <div id = "todo_greeting"></div>
        <div id = "todo_add"></div>
        <form id="todo_form">
        </form>
        <br />
        <div id="todo_show">
        </div>
      </div>
      <script src="js/clock.js" id="script_started"></script>
      <script src = "js/greeting.js"></script>
      <script src = "js/todo.js"></script>  
      <script src = "js/weather.js"></script>
      <script src = "js/background.js"></script>
    </body>
  </head>
</html>

CSS

background.css

body{
  background: linear-gradient(
    to right,
    rgba(232, 232, 232, 0.3),
    rgba(191, 191, 191, 0.3)),
    url("../imgs/img2.jpeg");
    background-size : cover;
}

clock.css

.clock{
  text-align : center;
  font-size : 150px;
  color : white;
  text-shadow: 2px 2px 9px rgb(90, 90, 90);
  }

greeting.css

.greeting {
  text-align : center;
  font-size : 40px;
  color : white;
}

todo.css

.todo_list {
  text-align : center;
  font-size : 20px;
  color : white;
}

#todo_input{
  text-align : center;
  width : 300px;
  height : 30px;
  border : none;
  background-color : rgba(0, 0, 0, 0);
  border-bottom : 2px solid white;
  color : white;
}

#todo_input:focus{
  text-align : center;
  outline : none;
  border : none;
  background-color : rgba(0, 0, 0, 0);
  border-bottom : 2px solid white;
  color : white;
}

input[type="checkbox"]{
  display : none;
}

input[type="checkbox"] + label span{
  display : inline-block;
  width : 24px;
  height : 24px;
  margin : -2px 10px 0 0;
  vertical-align : middle;
  background: url(checkbox.svg) left top no-repeat;
  cursor : pointer;
  background-size : cover;
}

input[type="checkbox"]:checked+ label span {
  background : url(checkbox.svg) -26px top no-repeat;
  background-size: cover;
}

weather.css

.weather{
  text-align : right;
  font-size : 15px;
  color : white;
}

JS

background.js

//const background = document.querySelector('.background');

function rand(min, max){
  return Math.floor(Math.random()*(max-min))+min;
}

function getRandomImage(){
  var random = rand(1, 31);

  //style = document.createElement('style');
  //style.backgroundImage = `"url('img${random}.jpeg')"`;
  //document.body.appendChild(style);

  //const url = `"url('imgs/img${random}.jpeg')"`;
  //console.log(url);
  var url = "url('imgs/img"+String(random)+".jpeg')";
  var gradient = "radial-gradient(rgba(58, 57, 57, 0.1), rgba(0, 0, 0, 0.3))";

  const width = screen.availWidth;
  const height = screen.availHeight;
  gradient = gradient + ", " + url;  

  console.log(width, height);
  document.body.style.backgroundImage = gradient;
  document.body.style.backgroundSize = 'cover';

}
getRandomImage();

clock.js

getTime = function(){
  var now = new Date();
  var year = now.getFullYear();
  var month = now.getMonth();
  var date = now.getDate();
  var hour = now.getHours();
  var min = now.getMinutes();
  var sec = now.getSeconds();
  
  var clock = document.querySelector(".clock").querySelector(".time");
  
  clock.innerHTML = `${hour<10 ? `0${hour}`:hour}:${min<10 ? `0${min}`:min}:${sec<10 ? `0${sec}`:sec}`;
}


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

init();

crawler.js

const puppeteer = require('puppeteer');
const axios = require('axios');
const fs = require('fs');

fs.readdir('../imgs', (err) => {
  if(err){
    console.error("imgs 폴더가 없어 imgs 폴더를 생성합니다.")
    fs.mkdirSync('../imgs');
  }
});

const crawler = async()=>{
  try{
    const browser = await puppeteer.launch({
      headless : false,
    });
    const page = await browser.newPage();
    await page.goto('https://unsplash.com/s/photos/summer?orientation=landscape');

    let result = [];
    while(result.length<=30){
      let srcs = await page.evaluate(()=>{
        window.scrollTo(0, 0);
        let imgs = [];
        const imgEls = document.querySelectorAll('._2UpQX');
        if(imgEls.length){
          imgEls.forEach((v)=>{
            const img = v;
            if(img&&img.currentSrc){
              imgs.push(img.currentSrc);
            }
            v.parentElement.removeChild(v);
          });
        }
        window.scrollBy(0, 100);
        setTimeout(()=>{
          window.scrollBy(0, 200);
        }, 500);
        return imgs;
      });

      result = result.concat(srcs);
      await page.waitForSelector('figure');
      //console.log('태그 로딩 완료');
    }
    var idx = 1;
    result.forEach(async(src) => {
      const imgResult = await axios.get(src.replace(/\?.*$/, ''), {
        responseType:'arraybuffer'
      });
      // 개발자도구 네트워크를 활용해 확장자 파악하기
      fs.writeFileSync(`../imgs/img${idx}.jpeg`, imgResult.data);
      idx++;
    })
    console.log(result);
    console.log(result.length);
    await page.close();
    await browser.close();
  }catch(err){
    console.log(err);
  }finally{

  }
};
crawler();

greeting.js

sayHello = function(){
  const now = new Date();
  const hour = now.getHours();

  var greeting = '';

  if(hour>=6 && hour <= 12){
    greeting = 'Good Morning, ';
  }
  else if(hour > 12 && hour < 18){
    greeting = 'Good Afternoon, ';
  }
  else{
    greeting = 'Good Evening, ';
  }

  var temp = document.querySelector('.greeting').querySelector('b');
  temp.innerHTML = `${greeting}진실`;
};

init = function(){
  sayHello();
  setInterval(sayHello, 360000);
}

init();

todo.js

var todo_list = document.querySelector('.todo_list');
var todo_greeting = document.querySelector('#todo_greeting');
var todo_form = document.querySelector('#todo_form');
var todo_show = document.querySelector('#todo_show');
var todo_add = document.querySelector('#todo_add');
var todo_checkboxes = document.querySelectorAll('input[type=checkbox]');
var toDos = [];

var showToDos = function(toDo, idx){
  const div = document.createElement('div');
  const checkbox = document.createElement('input');
  const design_label = document.createElement('label');
  const design_span = document.createElement('span');
  const content = document.createElement('span');
  const remove = document.createElement('span');

  div.id = idx;
  checkbox.type = 'checkbox';
  checkbox.id =`checkbox${idx}`;
  design_label.htmlFor =`checkbox${idx}`;

  content.innerText = toDo;
  content.className = 'content';
  remove.innerHTML = '&nbsp';
  remove.className = 'remove';


  design_label.appendChild(design_span);

  div.appendChild(checkbox);
  div.appendChild(design_label);
  div.appendChild(content);
  div.appendChild(remove);
  todo_show.appendChild(div);

 
  checkbox.addEventListener('change', (e)=>{
    var div = document.getElementById(idx);
     var content = div.querySelector('.content');
    if(e.target.checked){
      var content_cp = content.cloneNode(true);
      var del = document.createElement('del');
      del.className = 'del';
      del.appendChild(content_cp);
      div.replaceChild(del, content);
    }
    else{
      var del = div.querySelector('.del');
      var content = del.firstChild;
      div.replaceChild(content, del);
    }
  });

  remove.addEventListener('mouseout', ()=>{
    var div = document.getElementById(idx);
    var removeIcon = div.querySelector('.remove');
    removeIcon.innerHTML = '&nbsp';
  })
  remove.addEventListener('mouseover', ()=>{
    var div = document.getElementById(idx);
    var removeIcon = div.querySelector('.remove');
    removeIcon.innerHTML = ' X';
    removeIcon.addEventListener('click', ()=>{
      div.remove();
    })
  });

  //todo_checkboxes = document.querySelectorAll('input[type=checkbox]');
};

var loadToDos = function(){
  toDos.forEach((toDo, idx)=>{
    showToDos(toDo, idx);
  });
};

var addToDos = function(){
  var input = document.createElement('input');
  input.type = "text";
  input.id = "todo_input";

  todo_form.appendChild(input);
}

if(toDos.length==0){
  todo_greeting.innerHTML = 'What is your main focus for today?'
  addToDos();
}
else{
  
  loadToDos();
}

todo_form.addEventListener('submit', (e)=>{
  e.preventDefault();
  text = todo_input.value;
  toDos.push(text);
  showToDos(text, toDos.length);
  todo_add.innerHTML = 'add to do list';
  todo_greeting.innerHTML = '';
  todo_form.innerHTML = '';
});

todo_add.addEventListener('click', ()=>{
  addToDos();
});

weather.js

const weather = document.querySelector('.weather');
const weather_icon = weather.querySelector('#weather_icon');
const temperature = weather.querySelector('#temperature');
const city_name = weather.querySelector('#city_name');


const API_KEY = '194bda66412202a3ac76cc100fb66424';
const COORDS = "coords";

function getWeather(lat, lon){
  fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}`)
  .then((res)=>{
    return res.json();
  }).then((json)=>{
    var temp = +(Math.round(json.main.temp/10 + "e+2")  + "e-2");
    const place = json.name;
    const icon = json.weather[0].icon;

    weather_icon.innerHTML = `<img src="http://openweathermap.org/img/wn/${icon}@2x.png" / width="50">`;
    temperature.innerText = temp;
    city_name.innerText = place;

    weather_icon.appendChild(temperature);
    weather.appendChild(weather_icon);
    weather.appendChild(city_name);
  });
}

function saveCoords(coordsObj){
  localStorage.setItem(COORDS, JSON.stringify(coordsObj));
}

function handleGeoSuccess(position){
  const latitude = position.coords.latitude;
  const longitude = position.coords.longitude;
  const coordsObj = {
    latitude,
    longitude,
  };
  saveCoords(coordsObj);
}

function handleGeoError(){
  console.log('Not allowed');
}

function askForCoords(){
  navigator.geolocation.getCurrentPosition(handleGeoSuccess, handleGeoError);
}

function loadCoords(){
  const loadedCoords = localStorage.getItem(COORDS);
  if(loadedCoords === null){
    askForCoords();
  }
  else{
    const parseCoords = JSON.parse(loadedCoords);
    getWeather(parseCoords.latitude, parseCoords.longitude);
  }
}

function init(){
  loadCoords();
}

init();

❕ 크롤러는 zerocho님onyou loy124님의 코드를 참고해서 만들었습니다

profile
반갑습니다.
post-custom-banner

0개의 댓글