바닐라 JS로 크롬 앱 만들기

히치키치·2021년 6월 21일
0

2.3 : const and let

[1]

const a=5; //상수 : 값 변경시 오류 발생
const b=1;
let my_long_name="ayeon"; //변수

console.log(a+b);
console.log(a*b);
console.log(a/b);
console.log(my_long_name+" is my name.");

my_long_name="jangayeon";
console.log(my_long_name+"is my new name");

2.4 : Booleans

[1]

const amIFat=null;
let something;

console.log(amIFat); 
//null : 변수 안에 값이 없음을 확실히 하기 위해 의도적 사용
console.log(something); 
//undefinded : 메모리 존재 O, 값 할당 X

2.5 : Arrays

[1]

const mon="mon";
const tue="tue";
const wed="wed";
const thur="thur";
const fri="fri";
const sat="sat";


const string_dayOfweek=mon+tue+wed+thur+fri+sat;
const array_dayOfweek=[mon,tue,wed,thur,fri,sat];

console.log(string_dayOfweek);
console.log(array_dayOfweek);

//get item from array : zero indexing
console.log(array_dayOfweek[2]);

//add ne more dat to array
array_dayOfweek.push("sun");

console.log(array_dayOfweek);

2.6 : Object

[1]

const player={
    name:"ayeon",
    points:10,
    fat:true,
};
console.log(player);
console.log(player.name);
console.log(player["fat"]);

player.fat=false; 
player.points+=10;
//const -> player, 그 안의 propertys는 const 아님
console.log(player);

2.7 / 2.8 Functions

[1]

function sayhello(nameOfPerson,age){
    console.log("hello I am "+nameOfPerson);
    console.log("I am "+age+" years old");
};

sayhello("nico",10);
sayhello("dal",20);
sayhello("ayeon",30);

function add(a,b){
    console.log(a+b);
}
function div(a,b){
    console.log(a/b);
}
add();
add(5,2);
div(10,2);

[2]

const player={
    name : "nico",
    sayHello : function(otherPersonsName){
        console.log("hello "+otherPersonsName+" nice to meet you");
    }
};
player.sayHello("ayeon");

2.11 Returns

[1]

const calculator = {
    add : function(a, b){
        return a+b;
    },
    minus : function(a, b){
        return a-b;
    },
    divide : function(a, b){
        return a/b;
    },
    multiply : function(a, b){
        return a*b;
    },
}
    
const addResult = calculator.add(2,3);
const minusResult = calculator.minus(addResult,3);
const divideResult = calculator.divide(14,minusResult);
const multiplyResult = calculator.multiply(divideResult,5);

2.13 Conditionals

[1]

const age=prompt("How old are you?");

console.log(age);
console.log(typeof age);

//turn string into number
INT_age=parseInt(age); 
console.log(INT_age);
console.log(typeof INT_age);

[2]

const age=parseInt(prompt("How old are you?"));
console.log(age);
console.log(typeof age);

[3]

const age=parseInt(prompt("How old are you?"));

console.log(isNaN(age));

if (isNaN(age)){
    console.log("Plz write number");
}
else{
    console.log("Thank you for writing your number");
}

[4]

const age=parseInt(prompt("How old are you?"));

console.log(isNaN(age));

if (isNaN(age)){
    console.log("Plz write number");
}
else if(age<18){
    console.log("you are too young");
}
else{
    console.log("you can drink");
}

[5]

const age=parseInt(prompt("How old are you?"));

console.log(isNaN(age));

if (isNaN(age)){
    console.log("Plz write number");
}
else if(age<18){
    console.log("you are too young");
}
else if (age>=18 && age<=50){ // and
    console.log("you can drink");
}
else{
    console.log("you can't drink");
}

[6]

const age=parseInt(prompt("How old are you?"));

console.log(isNaN(age));

if (isNaN(age)){
    console.log("Plz write number");
}
else if(age<18){
    console.log("you are too young");
}
else if (age>=18 || age<=50){ // or
    console.log("you can drink");
}
else{
    console.log("you can't drink");
}

3.1 / 3.2 Search Elements

  • tag name : h1 : div : getElementByTagName
  • ID name : getElementById
  • class name : getElementByClassName
  • querySelector :

[1]

//app.js

const title = document.getElementById("title");
title.innerText="Got you"

console.log(title.id);
console.log(title.className);

[2]

//app.js
const hellos= document.getElementsByClassName("hello");
console.log(hellos);

//index.html
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" conetent="width=device-width, intial-scale=1.0">
        <link rel="stylesheet" href="style.css">
        <title>바닐라 Js로 크롬 웹 만들기 </title>
    </head>
    <body>
        <h1 class = "hello" >Grab me!</h1>
        <h1 class = "hello" >Grab me!</h1>
        <h1 class = "hello" >Grab me!</h1>
        <h1 class = "hello" >Grab me!</h1>
        <h1 class = "hello" >Grab me!</h1>
        <script src="app.js"></script>
    </body>
</html>

[3]

//app.js
const title=document.querySelector(".hello h1");
console.log(title);

//index.html
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" conetent="width=device-width, intial-scale=1.0">
        <link rel="stylesheet" href="style.css">
        <title>바닐라 Js로 크롬 웹 만들기 </title>
    </head>
    <body>
        <div class="hello">
            <h1>
                Grab me!
            </h1>
        </div>
        <script src="app.js"></script>
    </body>
</html>

[4]

//app.js

const title=document.querySelector(".hello:first-child");
title.innerText="bye";
console.log(title);

//index.html
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" conetent="width=device-width, intial-scale=1.0">
        <link rel="stylesheet" href="style.css">
        <title>바닐라 Js로 크롬 웹 만들기 </title>
    </head>
    <body>
        <div class="hello">
            <h1>hello</h1>
        </div>
        <div class="hello">
            <h1>nice to meet you</h1>
        </div>
        <div class="hello">
            <h1>bye</h1>
        </div>
        <script src="app.js"></script>
    </body>
</html>

3.3 / 3.4 / 3.5 Events

[1]

//app.js

const title=document.querySelector("div.hello:first-child h1");
function handleTitleClick(){
    title.style.color="blue";
    console.log("title was clicked!");
}
title.addEventListener("click",handleTitleClick);

//index.html
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" conetent="width=device-width, intial-scale=1.0">
        <link rel="stylesheet" href="style.css">
        <title>바닐라 Js로 크롬 웹 만들기 </title>
    </head>
    <body>
        <div class="hello">
            <h1>grab me 1!</h1>
        </div>
        <script src="app.js"></script>
    </body>
</html>

[2]

//app.js

const title=document.querySelector("div.hello:first-child h1");

console.log(title.innerText);
function handleTitleClick(){
    title.style.color="gray"; //스타일은 CSS로 바뀌는 것이 효율적
    console.log("title was clicked!");
}

function handlemouseEnter(){
    title.style.color="blue"; //스타일은 CSS로 바뀌는 것이 효율적
    console.log("mouse is here!");
    title.innerText="mouse i here";
}
function handlemouseLeave(){
    title.style.color="red"; //스타일은 CSS로 바뀌는 것이 효율적
    console.log("mouse is not here!");
    title.innerText="mouse is not here";
}
title.addEventListener("mouseenter",handlemouseEnter);
title.addEventListener("mouseleave",handlemouseLeave);
title.addEventListener("click",handleTitleClick);

//index.html
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" conetent="width=device-width, intial-scale=1.0">
        <link rel="stylesheet" href="style.css">
        <title>바닐라 Js로 크롬 웹 만들기 </title>
    </head>
    <body>
        <div class="hello">
            <h1>grab me 1!</h1>
        </div>
        <script src="app.js"></script>
    </body>
</html>

[3]

//app.js

const h1=document.querySelector("div.hello:first-child h1");

function handleTitleClick(){
    h1.style.color="gray"; //스타일은 CSS로 바뀌는 것이 효율적
    console.log("title was clicked!");
}

function handlemouseEnter(){
    h1.style.color="blue"; //스타일은 CSS로 바뀌는 것이 효율적
    console.log("mouse is here!");
    h1.innerText="mouse i here";
}
function handlemouseLeave(){
    h1.style.color="red"; //스타일은 CSS로 바뀌는 것이 효율적
    console.log("mouse is not here!");
    h1.innerText="mouse is not here";
}

function handleWindowResize(){
    document.body.style.backgroundColor="tomato";
}
function handleWindowCopy(){
    alert("copier");
}

function handleWindowOffline(){
    alert("SOS No Wifi");
}
function handleWindowOnline(){
    alert("Good Wifi Connection");
}

h1.addEventListener("mouseenter",handlemouseEnter);
h1.addEventListener("mouseleave",handlemouseLeave);
h1.addEventListener("click",handleTitleClick);

window.addEventListener("copy",handleWindowCopy);
window.addEventListener("resize",handleWindowResize);
window.addEventListener("offline",handleWindowOffline);
window.addEventListener("online",handleWindowOnline);

//index.html
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" conetent="width=device-width, intial-scale=1.0">
        <link rel="stylesheet" href="style.css">
        <title>바닐라 Js로 크롬 웹 만들기 </title>
    </head>
    <body>
        <div class="hello">
            <h1>grab me 1!</h1>
        </div>
        <script src="app.js"></script>
    </body>
</html>

3.6 / 3.7 / 3.8 CSS in Javascript

[1]

  • change color using Js
//app.js

const h1=document.querySelector("div.hello:first-child h1");

function handleTitleClick(){
    const currentColor = h1.style.color;
    let newcolor;
    if(currentColor==="blue"){
        newcolor="pink";
    }
    else{
        newcolor="blue";
    }
    h1.style.color=newcolor;
}


h1.addEventListener("click",handleTitleClick);

//index.html
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" conetent="width=device-width, intial-scale=1.0">
        <link rel="stylesheet" href="style.css">
        <title>바닐라 Js로 크롬 웹 만들기 </title>
    </head>
    <body>
        <div class="hello">
            <h1>grab me 1!</h1>
        </div>
        <script src="app.js"></script>
    </body>
</html>

[2]

  • replace class name
  • change color using css
//app.js

const h1=document.querySelector("div.hello:first-child h1");

function handleTitleClick(){
    const clickedClass="clicked";
    if(h1.className===clickedClass){
        h1.className="";
    }
    else{
        h1.className=clickedClass;
    }
}

h1.addEventListener("click",handleTitleClick);
//index.html
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" conetent="width=device-width, intial-scale=1.0">
        <link rel="stylesheet" href="style.css">
        <title>바닐라 Js로 크롬 웹 만들기 </title>
    </head>
    <body>
        <div class="hello">
            <h1 class="sexy-font">grab me 1!</h1>
        </div>
        <script src="app.js"></script>
    </body>
</html>
//style.css
body{
    background-color: beige;
}
h1 {
    color : cornflowerblue;
    transition: color .5s ease-in-out;
}
.clicked {
    color:tomato;
}
.sexy-font{
    font-family: 'apple-system', sans-serif;
}

[3]

  • .classList.contains : check whether class is contained
  • .classList.remove(): remove class
  • .classList.add() : add class
//app.js
const h1=document.querySelector("div.hello:first-child h1");

function handleTitleClick(){
    const clickedClass="clicked";
    if(h1.classList.contains(clickedClass)){
        h1.classList.remove(clickedClass);
    }
    else{
        h1.classList.add(clickedClass);
    }
}

h1.addEventListener("click",handleTitleClick);

//index.html
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" conetent="width=device-width, intial-scale=1.0">
        <link rel="stylesheet" href="style.css">
        <title>바닐라 Js로 크롬 웹 만들기 </title>
    </head>
    <body>
        <div class="hello">
            <h1 class="sexy-font">grab me 1!</h1>
        </div>
        <script src="app.js"></script>
    </body>
</html>

//style.css
body{
    background-color: beige;
}
h1 {
    color : cornflowerblue;
    transition: color .5s ease-in-out;
}
.clicked {
    color:tomato;
}
.sexy-font{
    font-family: 'apple-system', sans-serif;
}
  • .classList.toggle() : check if class exist then remove if not add
//app.js
const h1=document.querySelector("div.hello:first-child h1");

function handleTitleClick(){
    const clickedClass="clicked";
    h1.classList.toggle("clicked");
}

h1.addEventListener("click",handleTitleClick);

//index.html
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" conetent="width=device-width, intial-scale=1.0">
        <link rel="stylesheet" href="style.css">
        <title>바닐라 Js로 크롬 웹 만들기 </title>
    </head>
    <body>
        <div class="hello">
            <h1 class="sexy-font">grab me 1!</h1>
        </div>
        <script src="app.js"></script>
    </body>
</html>

//style.css
body{
    background-color: beige;
}
h1 {
    color : cornflowerblue;
    transition: color .5s ease-in-out;
}
.clicked {
    color:tomato;
}
.sexy-font{
    font-family: 'apple-system', sans-serif;
}

4.0 Input Values

  • make login button and get value from blank
바닐라 Js로 크롬 웹 만들기
Log In
//index.html
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" conetent="width=device-width, intial-scale=1.0">
        <link rel="stylesheet" href="style.css">
        <title>바닐라 Js로 크롬 웹 만들기 </title>
    </head>
    <body>
        <div id ="Login-form">
            <input type="text" placeholder="what is your name?" />
            <button>Log In</button>
        </div>
        <script src="app.js"></script>
    </body>
</html>

//app.js
const loginInput=document.querySelector("#Login-form input");
const loginButton=document.querySelector("#Login-form button");


function onLoginBtnClick(){
    console.dir(loginInput);
    console.log("click");
    console.log(loginInput.value);
}

loginButton.addEventListener("click",onLoginBtnClick);

4.1 Form Submission

  • check validation of user name

[1]

  • check formation of username in Js
//index.html
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" conetent="width=device-width, intial-scale=1.0">
        <link rel="stylesheet" href="style.css">
        <title>바닐라 Js로 크롬 웹 만들기 </title>
    </head>
    <body>
        <div id ="Login-form">
            <input type="text" placeholder="what is your name?" />
            <button>Log In</button>
        </div>
        <script src="app.js"></script>
    </body>
</html>

//app.js

const loginInput=document.querySelector("#Login-form input");
const loginButton=document.querySelector("#Login-form button");


function onLoginBtnClick(){

    const username=loginInput.value;
    if(username===""){
        alert("Plz write your name"); 
        //make user to see message
    }
    else if (username.length>15){
        alert("Your name is too long"); 
        //make user name is longer than 15 chars
    }
}

loginButton.addEventListener("click",onLoginBtnClick);

[2]

  • check formation of username in html
  • Error : form is being submitted all the time
//app.js

const loginInput=document.querySelector("#Login-form input");
const loginButton=document.querySelector("#Login-form button");


function onLoginBtnClick(){

    const username=loginInput.value;
    console.log(username);
}

loginButton.addEventListener("click",onLoginBtnClick);

//index.html
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" conetent="width=device-width, intial-scale=1.0">
        <link rel="stylesheet" href="style.css">
        <title>바닐라 Js로 크롬 웹 만들기 </title>
    </head>
    <body>
        <form id ="Login-form">
            <input 
                required
                maxlength="15"
                type="text" 
                placeholder="what is your name?" />
            <button>Log In</button>
        </div>
        <script src="app.js"></script>
    </body>
</html>

4.2 / 4.3 Events

[1]

  • using Event Object
  • default : enter -> submit webpage and refresh it
  • .preventDefault() : stop being refreshed as enter pressed
//app.js
const loginForm=document.querySelector("#Login-form");
const loginInput=document.querySelector("#Login-form input");


function onLoginSubmit(event){
    //detect submit event
    event.preventDefault();
    //prevent borrowser doing default activation (refreshing each time)
    console.log(event); //event infomation augument
    const username=loginInput.value;
    console.log(username);
}

loginForm.addEventListener("submit",onLoginSubmit);

//index.html
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" conetent="width=device-width, intial-scale=1.0">
        <link rel="stylesheet" href="style.css">
        <title>바닐라 Js로 크롬 웹 만들기 </title>
    </head>
    <body>
        <form id ="Login-form">
            <input 
                required
                maxlength="15"
                type="text" 
                placeholder="what is your name?" />
            <button>Log In</button>
        </div>
        <script src="app.js"></script>
    </body>
</html>

[2]

  • click event assciated with link
  • without .preventDefault after alert message show default function activated
//app.js

const loginForm=document.querySelector("#Login-form");
const loginInput=document.querySelector("#Login-form input");

const link = document.querySelector("a");

function onLoginSubmit(event){
    //detect submit event
    event.preventDefault();
    //prevent borrowser doing default activation (refreshing each time)
    console.log(event); //event infomation augument
    const username=loginInput.value;
    console.log(username);
}

function handleLinkClick(event){
    event.preventDefault();
    //preventing default action
    console.dir(event);
    //show info about click event
    alert("click!");
    //after showing alert then default action "go to hyperlink" done
}
loginForm.addEventListener("submit",onLoginSubmit);
link.addEventListener("click",handleLinkClick);

//index.html
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" conetent="width=device-width, intial-scale=1.0">
        <link rel="stylesheet" href="style.css">
        <title>바닐라 Js로 크롬 웹 만들기 </title>
    </head>
    <body>
        <form id ="Login-form">
        </form>
         <a href = "https://nomadcoders.co"> Go to Course</a>
        <script src="app.js"></script>
    </body>
</html>

4.4 Getting Username

[1]

//app.js
const loginForm=document.querySelector("#Login-form");
const loginInput=document.querySelector("#Login-form input");
const greeting=document.querySelector("#greeting");

const HIDDEN_CLASSNAME="hidden";

function onLoginSubmit(event){
    //detect submit event
    event.preventDefault();
    //prevent borrowser doing default activation (refreshing each time)
    const username=loginInput.value;
    loginForm.classList.add(HIDDEN_CLASSNAME);
    console.log(username);
    greeting.innerText=`hello ${username}`;
    //같은 코드 : greeting.innerText="hello "+username;
    greeting.classList.remove(HIDDEN_CLASSNAME);
}

loginForm.addEventListener("submit",onLoginSubmit);

//index.html
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" conetent="width=device-width, intial-scale=1.0">
        <link rel="stylesheet" href="style.css">
        <title>바닐라 Js로 크롬 웹 만들기 </title>
    </head>
    <body>
        <form id ="Login-form">
            <input 
                required 
                maxlength="15"
                type="text"
                placeholder="What is your name?"
            />
            <input type="submit" value="Log In"/>
        </form>
        <h1 id = "greeting" class="hidden"></h1>>
        <script src="app.js"></script>
    </body>
</html>

//style.css
body{
    background-color: beige;
}
h1 {
    color : cornflowerblue;
    transition: color .5s ease-in-out;
}
.clicked {
    color:tomato;
}
.hidden{
    display:none;
}

4.5 Saving Username

  • using localStorage to get username
  • localStorage.setItem(key,value)
  • getItem(key)
  • removeItem(key)
//app.js
const loginForm=document.querySelector("#Login-form");
const loginInput=document.querySelector("#Login-form input");
const greeting=document.querySelector("#greeting");

const HIDDEN_CLASSNAME="hidden";

function onLoginSubmit(event){
    //detect submit event
    event.preventDefault();
    //prevent borrowser doing default activation (refreshing each time)
    const username=loginInput.value;
    loginForm.classList.add(HIDDEN_CLASSNAME);
    localStorage.setItem("username",username);
    greeting.innerText=`hello ${username}`;
    //같은 코드 : greeting.innerText="hello "+username;
    greeting.classList.remove(HIDDEN_CLASSNAME);
}

loginForm.addEventListener("submit",onLoginSubmit);

4.6 Loading Username

  • if user is already in localStorage do not show form
//app.js
const loginForm=document.querySelector("#Login-form");
const loginInput=document.querySelector("#Login-form input");
const greeting=document.querySelector("#greeting");

const HIDDEN_CLASSNAME="hidden";
const USERNAME_KEY="username";

function onLoginSubmit(event){
    //detect submit event
    event.preventDefault();
    //prevent borrowser doing default activation (refreshing each time)
    const username=loginInput.value;
    loginForm.classList.add(HIDDEN_CLASSNAME);
    localStorage.setItem(USERNAME_KEY,username);
    paintGreetings(username);
}

function paintGreetings(username){
    greeting.innerText=`Hello ${username}`;
    greeting.classList.remove(HIDDEN_CLASSNAME);
}

const savedUsername=localStorage.getItem(USERNAME_KEY);

if(savedUsername===null){
    //show form
    loginForm.classList.remove(HIDDEN_CLASSNAME);
    loginForm.addEventListener("submit",onLoginSubmit);
}
else{
    //show the greeting
    paintGreetings(savedUsername);
}
//index.html
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" conetent="width=device-width, intial-scale=1.0">
        <link rel="stylesheet" href="style.css">
        <title>바닐라 Js로 크롬 웹 만들기 </title>
    </head>
    <body>
        <form class="hidden" id ="Login-form">
            <input 
                required 
                maxlength="15"
                type="text"
                placeholder="What is your name?"
            />
            <input type="submit" value="Log In"/>
        </form>
        <h1 id = "greeting" class="hidden"></h1>
        <script src="app.js"></script>
    </body>
</html>

5.0 Intervals

  • setInterval(function, millisec) : excuting the function in evry certain amount of time
//clock.js
const clock=document.querySelector("h2#clock");

clock.innerText="lalalall";

function sayHello(){
    console.log("hello");
}
setInterval(sayHello,5000);
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" conetent="width=device-width, intial-scale=1.0">
        <link rel="stylesheet" href="css/style.css">
        <title>바닐라 Js로 크롬 웹 만들기 </title>
    </head>
    <body>
        <form class="hidden" id ="Login-form">
            <input 
                required 
                maxlength="15"
                type="text"
                placeholder="What is your name?"
            />
            <input type="submit" value="Log In"/>
        </form>
        <h1 id = "greeting" class="hidden"></h1>
        <h2 id="clock">00 : 00</h2>
        <script src="js/greetings.js"></script>
        <script src="js/clock.js"></script>
    </body>
</html>

5.1 Timeouts and Dates

  • setTimeout(function, millisec) : run the function after certain amount of time
  • new Date() : get time Object
    -> methods : .getHours,.getMinutes,.getSeconds
//clock.js
const clock=document.querySelector("h2#clock");

function getClock(){
   const date=new Date();
   clock.innerText = `${date.getHours()} : ${date.getMinutes()} : ${date.getSeconds()}`;
}
getClock();
setInterval(getClock,1000);

5.2 PadStart

  • String.padStart(fixedLength,String to fill)
//clock.js
const clock=document.querySelector("h2#clock");

function getClock(){
   const date=new Date();
   const hours=String(date.getHours()).padStart(2,"0");
   const minutes=String(date.getMinutes()).padStart(2,"0");
   const sec=String(date.getSeconds()).padStart(2,"0");

   clock.innerText = `${hours} : ${minutes} : ${sec}`;
}
getClock();
setInterval(getClock,1000);

6.0 Quotes

  • Math.floor(Math.random()*10) : 0 ~ 9 랜덤 정수 추출
  • .length : 길이 : 하드코딩
  • const chosenImage=images[Math.floor(Math.random()*images.length)]; : 주어진 배열 중 원소 중 랜덤으로 배정 받기
//quotes.js
const quotes = [
    {
      quote: "The way to get started is to quit talking and begin doing.",
      author: "Walt Disney",
    },
    {
      quote: "Life is what happens when you're busy making other plans.",
      author: "John Lennon",
    },
    {
      quote:
        "The world is a book and those who do not travel read only one page.",
      author: "Saint Augustine",
    },
    {
      quote: "Life is either a daring adventure or nothing at all.",
      author: "Helen Keller",
    },
    {
      quote: "To Travel is to Live",
      author: "Hans Christian Andersen",
    },
    {
      quote: "Only a life lived for others is a life worthwhile.",
      author: "Albert Einstein",
    },
    {
      quote: "You only live once, but if you do it right, once is enough.",
      author: "Mae West",
    },
    {
      quote: "Never go on trips with anyone you do ntot love.",
      author: "Hemmingway",
    },
    {
      quote: "We wander for distraction, but we travel for fulfilment.",
      author: "Hilaire Belloc",
    },
    {
      quote: "Travel expands the mind and fills the gap.",
      author: "Sheda Savage",
    },
  ];
  
  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)];
  //.length를 이용해 하드 코딩
  
  quote.innerText = todaysQuote.quote;
  author.innerText = todaysQuote.author;
//index.html
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" conetent="width=device-width, intial-scale=1.0">
        <link rel="stylesheet" href="css/style.css">
        <title>바닐라 Js로 크롬 웹 만들기 </title>
    </head>
    <body>
        <form class="hidden" id ="Login-form">
            <input 
                required 
                maxlength="15"
                type="text"
                placeholder="What is your name?"
            />
            <input type="submit" value="Log In"/>
        </form>
        <h1 id = "greeting" class="hidden"></h1>
        <h2 id="clock">00 : 00 : 00</h2>
        <div id="quote">
            <span>

            </span>
            <span>
                
            </span>
        </div>
        <script src="js/greetings.js"></script>
        <script src="js/clock.js"></script>
        <script src="js/quotes.js"></script>
    </body>
</html>

6.1 Background

//background.js
const images=["0.jpeg","1.jpeg","2.jpeg"];

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

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

//index.html
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" conetent="width=device-width, intial-scale=1.0">
        <link rel="stylesheet" href="css/style.css">
        <title>바닐라 Js로 크롬 웹 만들기 </title>
    </head>
    <body>
        <form class="hidden" id ="Login-form">
            <input 
                required 
                maxlength="15"
                type="text"
                placeholder="What is your name?"
            />
            <input type="submit" value="Log In"/>
        </form>
        <h1 id = "greeting" class="hidden"></h1>
        <h2 id="clock">00 : 00 : 00</h2>
        <div id="quote">
            <span>

            </span>
            <span>
                
            </span>
        </div>
        <script src="js/greetings.js"></script>
        <script src="js/clock.js"></script>
        <script src="js/quotes.js"></script>
        <script src="js/background.js"></script>
    </body>
</html>
  • image 소스 추가됨

7.0 Setup

  • javascript 이용해 <form id="todo-form>과 <ul id="todo-list> 가져와서 javascript에서 요소 추가
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" conetent="width=device-width, intial-scale=1.0">
        <link rel="stylesheet" href="css/style.css">
        <title>바닐라 Js로 크롬 웹 만들기 </title>
    </head>
    <body>
        <form class="hidden" id ="Login-form">
            <input 
                required 
                maxlength="15"
                type="text"
                placeholder="What is your name?"
            />
            <input type="submit" value="Log In"/>
        </form>
        <h1 id = "greeting" class="hidden"></h1>
        <form id="todo-form">
            <input type="text" placeholder="Write a To Do and Press Enter" required>
        </form>
        <ul id="todo-list"> </ul>
        <h2 id="clock">00 : 00 : 00</h2>
        <div id="quote">
            <span>

            </span>
            <span>
                
            </span>
        </div>
        <script src="js/greetings.js"></script>
        <script src="js/clock.js"></script>
        <script src="js/quotes.js"></script>
        <script src="js/background.js"></script>
        <script src="js/todo.js"></script>
    </body>
</html>
  • const toDoForm=document.getElementById("todo-form");
  • const toDoInput=toDoForm.querySelector("#todo-form input");
    : .getElementByIdtodo-form 받아오고 .querySelector로 받아 온 todo-form에서 input 가져오기
const toDoForm=document.getElementById("todo-form");
const toDoList=document.getElementById("todo-list");

const toDoInput=toDoForm.querySelector("#todo-form input");

function handleToDoSubmit(event){
    event.preventDefault();
    const newTodo=toDoInput.value;
    //copy current value of input to new variable
    toDoInput.value="";
}

toDoForm.addEventListener("submit",handleToDoSubmit);  

7.1 Adding ToDos

  • grab the value and send to function as augment
    //todo.js
    const toDoForm = document.getElementById("todo-form");
    const toDoInput = document.querySelector("#todo-form input");
    const toDoList = document.getElementById("todo-list");

function paintToDo(newTodo) {
const li = document.createElement("li");
const span = document.createElement("span");
li.appendChild(span);
span.innerText = newTodo;
toDoList.appendChild(li);
}

function handleToDoSubmit(event) {
event.preventDefault();
const newTodo = toDoInput.value;
toDoInput.value = "";
paintToDo(newTodo);
}

toDoForm.addEventListener("submit", handleToDoSubmit);

//index.html

바닐라 Js로 크롬 웹 만들기

00 : 00 : 00

    7.2 Deleting To Dos

    • 삭제 버튼 추가 -> 클릭하면 삭제 이벤트 발생
    • target Element의 parentelement를 찾아서 삭제 이벤트 진행
    const toDoForm = document.getElementById("todo-form");
    const toDoInput = document.querySelector("#todo-form input");
    const toDoList = document.getElementById("todo-list");
    
    function deleteToDo(event){
      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);
    }
    
    function handleToDoSubmit(event) {
      event.preventDefault();
      const newTodo = toDoInput.value;
      toDoInput.value = "";
      paintToDo(newTodo);
    }
    
    toDoForm.addEventListener("submit", handleToDoSubmit);
    

    7.3 / 7.4 / 7.5 Saving and Loading To Dos

    • localStorage.setItem() : saving value
    • JSON.stringify() : save value as string
    • JSON.parse() : get string to array
    • .foreach() : excute function for each item in array
    //index.html
    const toDoForm = document.getElementById("todo-form");
    const toDoInput = document.querySelector("#todo-form input");
    const toDoList = document.getElementById("todo-list");
    
    const toDos=[];
    const TODOS_KEY="todos";
    
    function saveToDos(){
      //put array in localstorage
      localStorage.setItem(TODOS_KEY,JSON.stringify(toDos));
    }
    
    function deleteToDo(event){
      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);
    }
    
    function handleToDoSubmit(event) {
      event.preventDefault();
      const newTodo = toDoInput.value;
      toDoInput.value = "";
      toDos.push(newTodo);
      //할 일 입력할 때마다 toDos에 추가됨
      paintToDo(newTodo);
      saveToDos();
    }
    
    function sayHello(item){
      //get element form array
      console.log("this is the turn of ", item);
    }
    
    toDoForm.addEventListener("submit", handleToDoSubmit);
    
    const savedToDos=localStorage.getItem(TODOS_KEY);
    
    if (savedToDos !== null){
      const parsedToDos=JSON.parse(savedToDos);
      parsedToDos.forEach(sayHello);
    }
    • run iteration with shortcut ver.
    const toDoForm = document.getElementById("todo-form");
    const toDoInput = document.querySelector("#todo-form input");
    const toDoList = document.getElementById("todo-list");
    
    const toDos=[];
    const TODOS_KEY="todos";
    
    function saveToDos(){
      //put array in localstorage
      localStorage.setItem(TODOS_KEY,JSON.stringify(toDos));
    }
    
    function deleteToDo(event){
      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);
    }
    
    function handleToDoSubmit(event) {
      event.preventDefault();
      const newTodo = toDoInput.value;
      toDoInput.value = "";
      toDos.push(newTodo);
      //할 일 입력할 때마다 toDos에 추가됨
      paintToDo(newTodo);
      saveToDos();
    }
    
    
    toDoForm.addEventListener("submit", handleToDoSubmit);
    
    const savedToDos=localStorage.getItem(TODOS_KEY);
    
    if (savedToDos !== null){
      const parsedToDos=JSON.parse(savedToDos);
      parsedToDos.forEach((item)=>console.log("this is the turn of ",item));
    }
    
    • iteration's augment can be function
    • chang "adding function" in local storage array's replace to append
    const toDoForm = document.getElementById("todo-form");
    const toDoInput = document.querySelector("#todo-form input");
    const toDoList = document.getElementById("todo-list");
    
    let toDos=[];
    // use let data type to update
    const TODOS_KEY="todos";
    
    function saveToDos(){
      //put array in localstorage
      localStorage.setItem(TODOS_KEY,JSON.stringify(toDos));
    }
    
    function deleteToDo(event){
      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);
    }
    
    function handleToDoSubmit(event) {
      event.preventDefault();
      const newTodo = toDoInput.value;
      toDoInput.value = "";
      toDos.push(newTodo);
      //할 일 입력할 때마다 toDos에 추가됨
      paintToDo(newTodo);
      saveToDos();
    }
    
    
    toDoForm.addEventListener("submit", handleToDoSubmit);
    
    const savedToDos=localStorage.getItem(TODOS_KEY);
    
    if (savedToDos !== null){
      const parsedToDos=JSON.parse(savedToDos);
      toDos=parsedToDos;
      parsedToDos.forEach(paintToDo);
    }
    

    7.6 / 7.7 / 7.8 Deleteing To Dos part

    • adapt delete function in Local Storage
    • set Object : id & text
    • get id to delet todo element
    • Date.now() : use to set id number
    const toDoForm = document.getElementById("todo-form");
    const toDoInput = document.querySelector("#todo-form input");
    const toDoList = document.getElementById("todo-list");
    
    let toDos=[];
    // use let data type to update
    const TODOS_KEY="todos";
    
    function saveToDos(){
      //put array in localstorage
      localStorage.setItem(TODOS_KEY,JSON.stringify(toDos));
    }
    
    function deleteToDo(event){
      const li=event.target.parentElement;
      console.log(li.id);
      li.remove();
    }
    
    
    function paintToDo(newTodo) {
      const li = document.createElement("li");
      li.id=newTodo.id;
      const span = document.createElement("span");
      span.innerText = newTodo.text;
      const button =document.createElement("button");
      button.innerText="❌";
      button.addEventListener("click",deleteToDo);
      li.appendChild(span);
      li.appendChild(button);
      
      toDoList.appendChild(li);
    }
    
    function handleToDoSubmit(event) {
      event.preventDefault();
      const newTodo = toDoInput.value;
      toDoInput.value = "";
      const newTodoObj={
        text:newTodo,
        id:Date.now(),
      };
      toDos.push(newTodoObj);
      //할 일 입력할 때마다 toDos에 추가됨
      paintToDo(newTodoObj);
      saveToDos();
    }
    
    
    toDoForm.addEventListener("submit", handleToDoSubmit);
    
    const savedToDos=localStorage.getItem(TODOS_KEY);
    
    if (savedToDos !== null){
      const parsedToDos=JSON.parse(savedToDos);
      toDos=parsedToDos;
      parsedToDos.forEach(paintToDo);
    }
      
    • filter : 지우고 싶은 item 제외하고 새로운 array 만들기
      array의 item을 유지하고 싶은 경우 true 반환
    const todos=[{text:"lalala"},{text:"lololo"}];
    function sexyFilter(todo){ return todo.text!=="lololo"};
    todos.filter(sexyFilter); 
    • parseInt() : change string to Int
    const toDoForm = document.getElementById("todo-form");
    const toDoInput = document.querySelector("#todo-form input");
    const toDoList = document.getElementById("todo-list");
    
    let toDos=[];
    // use let data type to update
    const TODOS_KEY="todos";
    
    function saveToDos(){
      //put array in localstorage
      localStorage.setItem(TODOS_KEY,JSON.stringify(toDos));
    }
    
    function deleteToDo(event){
      const li=event.target.parentElement;
      li.remove();
      toDos=toDos.filter((toDo)=>toDo.id!== parseInt(li.id));
      //each element on toDo's database
      saveToDos();
    }
    
    
    function paintToDo(newTodo) {
      const li = document.createElement("li");
      li.id=newTodo.id;
      const span = document.createElement("span");
      span.innerText = newTodo.text;
      const button =document.createElement("button");
      button.innerText="❌";
      button.addEventListener("click",deleteToDo);
      li.appendChild(span);
      li.appendChild(button);
      
      toDoList.appendChild(li);
    }
    
    function handleToDoSubmit(event) {
      event.preventDefault();
      const newTodo = toDoInput.value;
      toDoInput.value = "";
      const newTodoObj={
        text:newTodo,
        id:Date.now(),
      };
      toDos.push(newTodoObj);
      //할 일 입력할 때마다 toDos에 추가됨
      paintToDo(newTodoObj);
      saveToDos();
    }
    
    
    toDoForm.addEventListener("submit", handleToDoSubmit);
    
    const savedToDos=localStorage.getItem(TODOS_KEY);
    
    if (savedToDos !== null){
      const parsedToDos=JSON.parse(savedToDos);
      toDos=parsedToDos;
      parsedToDos.forEach(paintToDo);
    }
      

    8.0 / 8.1 Geolocation

    • navigator 이용
    • get geolocation of user
    • getCurrentPosition(인자1, 인자2) :
      인자 1 -> what function to be excuted if no Error
      인자 2 -> what function to be excuted if Error exist
    • api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API key}
    • fetch : 실제로 url에 가지 않고 JavaScript가 대신 url을 부름
      const API_KEY="cb885eb10dc47392d636edbc7b0c5380";

    function onGeoOk(position){

    //get position
    const lat=position.coords.latitude;
    const lon=position.coords.longitude;
    console.log("You live in",lat,lon);
    const url=`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=metric`;
    //&units=metric 추가해서 화씨 온도 -> 섭씨 온도 변환
    fetch(url).then(response => response.json()).then(data=>{
        const weatherContainer=document.querySelector("#weather span:first-child");
        const cityContainer=document.querySelector("#weather span:last-child");
        cityContainer.innerText=data.name,
        weatherContainer.innerText=`${data.weather[0].main}/${data.main.temp}`;
        } );

    }
    function onGeoError(){
    alert("Can't find you. No weather for you");
    }

    navigator.geolocation.getCurrentPosition(onGeoOk,onGeoError)

    0개의 댓글