상세 컨텐츠

본문 제목

바닐라 필기(2) ch.5 clock & ch.6 quotes ~

본문

setInterval(function, time);

setTimeout(function, time);

const date = new Date();
console.log(date.getDate()); //25
console.log(date.getFullYear()); //2022
console.log(date.getHours()); //16
console.log(date.getMinutes()); //56
console.log(date.getSeconds()); //25

5.2 PadStart

(method) String.padStart(maxLength: number, fillString?: string | undefined): string

Pads the current string with a given string (possibly repeated) so that the resulting string reaches a given length. The padding is applied from the start (left) of the current string.

두자리숫자 만들기

console.log(String("2").padStart(2, 0));
const clock = document.querySelector("h2#clock");

const getClock = () => {
  const date = new Date();
  const setPad = (num) => String(num).padStart(2, "0");

  clock.innerText = `${setPad(date.getHours())} : ${setPad(
    date.getMinutes()
  )} : ${setPad(date.getSeconds())}`;
};

getClock();
setInterval(getClock, 1000);

6.0 quotes

const quotes = [
  {
    quote: "수고하고 무거운 짐 진 자들아 다 내게로 오라 내가 너희를 쉬게 하리라",
    author: "마태복음 11 : 28",
  },
  {....},
  ...
];

const quote = document.querySelector("#quote span:first-child");
const author = document.querySelector("#quote span:last-child");

const todaysQuote = quotes[Math.floor(Math.random() * quotes.length)];
quote.innerText = todaysQuote.quote;
author.innerText = todaysQuote.author;

6.1 background image

  • createElement
const images = ["0.jpeg", "1.jpeg", "2.jpeg"];

const chosenImage = images[Math.floor(Math.random() * images.length)];

const bgImage = document.createElement("img");
bgImage.src = `/img/${chosenImage}`;

document.body.appendChild(bgImage);

>> 배경으로 하려면

const bgImage = document.createElement("div");
bgImage.style = `
background-image:url("/img/${chosenImage}");
opacity:0.5;
position:absolute;
top:0;
bottom:0;
right:0;
left:0;
background-repeat: no-repeat;
background-size: cover;
z-index:-1;`;

document.body.appendChild(bgImage);

---------------------------or
bgImage.classList.add("randomBg");
bgImage.style = `background-image:url("/img/${chosenImage}");`;
-----css--------
.randomBg {    
opacity:0.5;
position:absolute;
top:0;
bottom:0;
right:0;
left:0;
background-repeat: no-repeat;
background-size: cover;
z-index:-1;
}

 

7. Todo List

7.2 event.target

- 이벤트일어난 요소의 세부사항 쪼로록 보여줌 (cosole.log(event.target)

function deleteToDo(event){
  //console.dir(event.target.parentElement.innerText);
    const li = event.target.parentElement;  // <<<
    li.remove();
}

function paintToDo(newTodo){
    const li = document.createElement("li");
    const span = document.createElement("span");
    span.innerText = newTodo;
    const button = document.createElement("button");
    button.innerText = "❌";
    button.addEventListener("click", deleteToDo);
    li.appendChild(span);
    li.appendChild(button);
    toDoList.appendChild(li);
}

7.3 JSON.stringify

const toDos = [];

localStorage.setItem("todos", JSON.stringify(toDos));    <<    <<


JSON.parse(localStorage.getItem("todos"))    <<    <<
// >> (5) ['abc', 'd', 'df', 'd', 'df']
localStorage.getItem("todos")
// >> '["abc","d","df","d","df"]'
  •  
  • stringify 없이 그냥 toDos 넣으면 문자열로 들어감 ( ["a", "b"] >> a,b ) 
  • 오오.. 저걸로 강제로 "/n" 이런식으로 바꿔서 string이지만 리스트모양 유지한채로 저장시켜줌

 

3. forEach & arrow function

const savedToDos = localStorage.getItem(TODOS_KEY);

if(savedToDos !== null){
    const parsedToDos = JSON.parse(savedToDos);
    parsedToDos.forEach(sayHello);
    // parsedToDos.forEach((item) => console.log("this is the turn of", item)); : 한줄로바꾸기

}

파라미터로 list넣으면 쪼로록 실행함

arrow 함수 정리 : https://inpa.tistory.com/entry/JS-%F0%9F%93%9A-%EC%9E%90%EB%B0%94%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8-%ED%99%94%EC%82%B4%ED%91%9C-%ED%95%A8%EC%88%98-%EC%A0%95%EB%A6%AC

 

[JS] 📚 자바스크립트 화살표 함수 💯 완벽 정리

​ 화살표 함수 ​함수 표현식보다 단순하고 간결한 문법으로 함수를 만들 수 있는 방법이 있습니다. ​ 바로 화살표 함수(arrow function)를 사용하는 것입니다. 화살표 함수라는 이름은 문법의 생

inpa.tistory.com

7.6 랜덤id 부여하기

  const newTodoObj = {
    text: newTodo,
    id: Date.now(),
  }
  toDos.push(newTodoObj);

4. filter

toDos = toDos.filter(toDo => toDo.id !== parseInt(li.id));
/*
toDo => toDo.id !== parseInt(li.id) = 
function(toDO){
	return toDo.id !== parseInt(li.id);
}
*/

toDos : []

filter 에서 true인 요소들만 []에 포함되어 리턴됨

 

8. weather api

geolocation.getCurrentPosition

https://developer.mozilla.org/ko/docs/Web/API/Geolocation/getCurrentPosition

 

Geolocation.getCurrentPosition() - Web API | MDN

Geolocation.getCurrentPosition() 메서드는 장치의 현재 위치를 가져옵니다.

developer.mozilla.org

  •  
  • fetch도 사용함

기온 단위변경시 parameter에 units추가

const API_KEY = "2d754e3bcb4bde7f7bc5bc0e87907a34";
const weather = document.querySelector("#weather span:first-child");
const city = document.querySelector("#weather span:last-child");

function onGeoOk(position){
    const lat = position.coords.latitude;
    const lon = position.coords.longitude;
    const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=metric`;
    fetch(url)
    .then(response => response.json())
    .then(data => {
        city.innerText = data.name;
        weather.innerText = `${data.weather[0].main} / ${data.main.temp}`;
    });
}
function onGeoError(){
    alert("Can't find you. No weather for you.");
}

navigator.geolocation.getCurrentPosition(onGeoOk,onGeoError);

api key : 사이트에 자기아이디 가서 찾아보면 있음

https://openweathermap.org/api

 

Weather API - OpenWeatherMap

Please, sign up to use our fast and easy-to-work weather APIs. As a start to use OpenWeather products, we recommend our One Call API 3.0. For more functionality, please consider our products, which are included in professional collections.

openweathermap.org

 

'노마드 > 바닐라&csslayout & 코코아톡 & 그림앱' 카테고리의 다른 글

그림 (2)  (0) 2022.08.03
그림(1)  (0) 2022.08.01
코코아톡 6.0~ 클론시작  (0) 2022.07.11
코코아톡 필기1  (0) 2022.07.05
CSS Layout (4) project_clone coding 필기  (0) 2022.06.29

관련글 더보기

댓글 영역