상세 컨텐츠

본문 제목

바닐라 필기(1) 1~4

본문

  1. 함수
    • parseInt("15")  >> 숫자아닌거 들어오면 NaN return
    • isNaN(agr) >> true / false : 숫자아니면 true (not a number)
    • a && b    //    a || b
  2. 객체접근방법 2가지
const player = {
	name: "nico",
    points: 10,
    fat: true,
};

console.log(player.name);
console.log(player["name"]);
-------------------------------
var a = {
  b  : 1,
  c  : 2
}
for (key in a) {
 console.log(a.key) // undefined, undefined
 console.log(a[key])// 1,2
}

3.0 console.dir

console.dir(document);
documnet.title;

3.1 

document.getElementById("title");
>> <h1 id="title">Grab me!</h1> 통째로 나옴

const title = document.getElementById("title");
console.dir(title);
console.log(title.className);~~~

3.2 querySelector >> 하나만 return, querySelectorAll >> 전부다 return

const hellos = document.getElementsByClassName("hello");
const title = document.querySelector(".hello h1");

3.3 Events   // style 

const title = document.querySelector("#abc:first-child h1");
title.style.color = "blue";

function handleTitleClick(){
	title.style.color = "blue";
}
title.addEventListener("click", handleTitleClick)

3.4 원하는 이벤트 구글링 :: 칠거치고 mdn 넣으삼,

console.dir(title) 로 치면 콘솔에 on~~ 하는거 = 이벤트임>> onABC >> title.addEventListener("ABC", ~~);

 

3.5 이벤트감지 두가지방법

title.addEventListener("click", abc);  >>이걸 더 선호함
>>  .removeEventListener("~~) 가능하니까 ㅇㅇ
=
title.onclick = abc;
  • resize 이벤트(window event)
function handleWindowResize(){
	document.body.style.backgroundColor = "black";
}

window.addEventListener("resize", handleWindowResize);

3.6~3.8 css in js

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

h1.addEventListener("click", handleTitleClick);
  • 자주쓰이는 중요단어>> 그냥 "abc"이렇게 여러군데쓰지말고, 변수에 담아서 쓰기
[style.css]
body {
	background-color: beige;
}
h1 {
	color: blue;
}
.active {
	color: tomato;
}
------------------
[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);
  • 여러 클래스중 하나만 지우기 (클래스바꾸는 2가지방법 : className, classList)
    • className :: 모든 클래스 변경함
    • classList : 리스트로 간주함 >> 함수많음ㅎ
function handleTitleClick(){ 
	const clickedClass = "clicked";
    if(h1.classList.contains(clickedClass)){   >>>@@
    	h1.classList.remove(clickedClass);  >>>@@
    }else {
    	h1.classList.add(clickedClass);       >>>@@
    }
}
  • toggle function>> class 추가하거나 제거하거나 알아서 해주는 굿펑션
function handleTitleClick(){ 
    h1.classList.toggle("clicked");
}

4. Login

4.1 input values  >> element.value

//import "./style.css";

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

function onLoginBtnClick() {
    //console.dir(loginInput); >> 쪼로록 뜸
    console.log(loginInput.value);    >>> return input value 
    console.log("clicked");
}

loginButton.addEventListener("click", onLoginBtnClick);

---------------------------------
function onLoginBtnClick() {
    const username = loginInput.value;

        if(username === ""){
            alert("plz write your name");
        } else if (username.length >= 7){
            alert("Your name is too long");
        }
}

loginButton.addEventListener("click", onLoginBtnClick);

>>>>>>> 이렇게 할필요 없이 밑에처럼 하면됨
<input type="text" placeholder="What is your name?" required maxlength="15" />

4.2 events (1)

  • form 자동 submit막기 : arg.preventDefault();
const loginForm = document.querySelector("#login-form");

function onLoginSubmit(event) {// 이벤트 발생한 객체에대해 arg로전달받음
    event.preventDefault();  //     <<<<<<<<<<<<<<<<<<<<< form의 기본동작 : submit
}
loginForm.addEventListener("submit", onLoginSubmit);
------------------------
<form id="login-form" >
      ~~
</form>

4.4 events (3) form 숨기기 : loginForm.classList.add(HIDDEN_CLASSNAME);

[ styles.css ] 
.hidden {
    display: none;
}
-------------------------------
[ index.html ]
<form id="login-form">
      <input type="text" placeholder="What is your name?" required maxlength="15" />
      <button>Log In</button>
</form>
<h1 id="greeting" class="hidden"></h1>
-------------------------------
[ index.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(tomato) {    
    tomato.preventDefault();  // 
    loginForm.classList.add(HIDDEN_CLASSNAME);  <<<<<<<<<<<<<<<<<<<<<
    const username = loginInput.value;
    greeting.innerText = `hello ${username}`;  
    greeting.classList.remove(HIDDEN_CLASSNAME);  <<<<<<<<<<<<<<<<<<<<<
}

loginForm.addEventListener("submit", onLoginSubmit);

4.5~4.6 saving, loading username << local storage

  • localStorage.setItem  , .getItem, removeItem, .clear()
const username = loginInput.value;
localStorage.setItem("username",username;  >>>> (key, value)
  • .getItem
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";    >>>>>>>>>>>>>> key값 항상 동일함

function onLoginSubmit(event) {// 이벤트 발생한 요소에대해 arg로전달받음    
    event.preventDefault();  // 
    loginForm.classList.add(HIDDEN_CLASSNAME);        
    const username = loginInput.value;

    localStorage.setItem(USERNAME_KEY,username);
    paintGreetings();             >>>>>>>>>>>>> 기존 2줄을 함수로 바꿈
}

function paintGreetings(username){   >>>>> h1 태그용 함수
	const username = localStorage.getItem(USERNAME_KEY); 
    greeting.classList.remove(HIDDEN_CLASSNAME);
    greeting.innerText = `hello ${username}`;
}

const savedUsername = localStorage.getItem(USERNAME_KEY);   >>>>>>>>>.getItem(key)

if(savedUsername === null){
    //show the form 
    loginForm.classList.remove(HIDDEN_CLASSNAME);
    loginForm.addEventListener("submit", onLoginSubmit);
}else {
    // show the greeting
    paintGreetings();
}




===========================================================
<form id="login-form" class="hidden"></form>       >>>>> 둘다 hidden 으로 시작
<h1 id="greeting" class="hidden"></h1>


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

코코아톡 필기1  (0) 2022.07.05
CSS Layout (4) project_clone coding 필기  (0) 2022.06.29
CSS Layout (3) scss  (0) 2022.06.25
CSS Layout 필기(2) grid  (0) 2022.06.17
CSS Layout 필기 (1) flex  (0) 2022.06.16

관련글 더보기

댓글 영역