#2.0 Your first JS Function
console.log
incoInfo.favFood
비슷하다.
console 은 Object 이다. console이라는 Object 와 log 라는 function(key) 가 있는것
function(argument)
function sayHello (name) {
console.log('Hello ' + name);
}
sayHello("sejin");
#2.1 More Function Fun
sexy string~
'', "" , ``
자바 스크립트에서는 "(따옴포)" 도 스트링이고 '(싱글 따옴표)' 도 스트링이다.
기존 스트링 방식 에서는
ex ) "Hello " + name + "you are " + age + ... 불편하다.
대신 백틱(`)을 사용할 수 있는데 띄어쓰기도 바로 반영되어 편리하다.
function sayHello (name, age) {
console.log(`Hello ${name} you are ${age} years old`);
}
sayHello('sejin', 10);
함수 이용하기, console.log() 는 리턴값을 가지지 않아 undefinded 가 발생한다.
const calculator = {
plus : function(a,b){
return a + b;
}
}
const result = calculator.plus(5,5);
console.log(result);
#2.2 JS DOM Functions
자바스크립트가 HTML 을 위해 어떻게 존재하는가?
css 에서 html 의 id 를 가져가려면 #
document 도 Object 이다. 로그를 찍으면 아래처럼 나온다
Object 이기 때문에
const title = document.getElementById("title");
console.log(title);
Dom을 통해서 가져온 아이디 정보에 대한 로그를 찍어 보면 객체 정보를 출력할수 있는데.
내용을 보면.. Id에 속해있는 해당 태그를 가져올수 있다(압축된놈)!
`JavaSctipt 는 네 HTML에 있는 모든 요소를 가지고 올거야. 그리고 그걸 객체로 바꿀거야
자바스크립트는 너의 html 태그를 가져다가 객체로 만들거야.`
객체는 많은 키를 가지고 있다는 것알 알아야해. console의 .log, .error, .name 처럼
아래는 JavaScript 이용해서 HTML 변경하기!
const title = document.getElementById("title");
title.innerHTML ="Hi! From JS";
document.title = "something";
console.log(title);
이게 바로 자바스크립트의 힘이지!
우리가 배울 모든 함수들은(우리가 찾게 될 모든 객체들의 함수들) DOM(Document Object Model) 형태로 변경 가능하다. 페이지에서 자바스크립트로 선택한것은 객체가 되는것.
#2.2 Modifying the DOM with JS
# console.dir(title)
const title = document.getElementById("title");
title.innerHTML = "Hi! From JS";
title.style.color = "blue";
console.dir(title);
이런식으로 자바스크립트를 이용하여 HTML 을 조종할수 있다
conseol.dir(document) 를 하게 되면 document 의 모든 정보를 알려준다.
document.querySelector(".title") // 클래스로 찾고 싶을때
document.querySelector("#title") // id 로 찾고 싶을때
const title = document.querySelector("#title");
title.innerHTML = "Hi! Hi HI hi";
title.style.color = "blue";
#2.4 Events and event handlers
자바스크립트는 단지 css 의 속성을 변경하기 위해 만들어 지지 않았어. 자바 스크립트는 이벤트에 반응하기 위해서 만들어 졌어
웹사이트에서 반응하는 이벤트 : click, resize, submit, input change, load, before closing printing
1. window event 에서는 Resize
: addEventListener("resize", handleResize) 형태는 윈도우 사이즈가 변경될때만 호출
: addEventListener("resize", handleResize()) 형태는 즉시 호출
function handleResize(){
console.log("I have been resized")
}
window.addEventListener("resize", handleResize);
event 를 추가해보자.
const title = document.querySelector("#title");
function handleResize(event){
console.log(event);
}
window.addEventListener("resize", handleResize);
# event 는 어디서 오는가? 이벤트를 다룰 함수를 만들때 마다 자바스크립트가 자동적으로 함수를 객체에 붙인다.
2. "click" 이벤트를 사용해 보자
const title = document.querySelector("#title");
function handleClick(){
title.style.color = "red";
}
title.addEventListener("click", handleClick);
.. form 에는 submit 이벤트
#2.5 if, else, and, or
if (condition && condition)
if (condition || condition)
prompt("what is you name?"); // 알림창 뛰을수 있지만 오래된 기능,
더 좋은폼으로 커스텀마이즈 할수 있는 방법이 있다.
const age = prompt("How old are you?");
console.log(age)
if(age > 18 && age < 21){
console.log("You can dirink but you should not");
}else if (age > 21) {
console.log("go ahead");
}else {
console.log("too young");
}
const title = document.querySelector("#title");
function handleClick(){
title.style.color = "red";
}
title.addEventListener("click", handleClick);
const BASE_COLOR = "rgb(52, 73, 94)";
function init() {
title.style.color = BASE_COLOR;
title.addEventListener("click", handleClick);
}
init();
console.log(title.style.color);
init이 내장함수?
색은 보통 저렇게 대문자로
const title = document.querySelector("#title");
const BASE_COLOR = "rgb(52, 73, 94)";
const OTHER_COLOR = "#7f8c8d";
function handleClick(){
const currentColor = title.style.color;
if(currentColor === BASE_COLOR) {
title.style.color = OTHER_COLOR;
}else{
title.style.color = BASE_COLOR;
}
}
function init() {
title.style.color = BASE_COLOR;
title.addEventListener("mouseenter", handleClick);
}
init();
#2.6 DOM- if else - Function practice
event 의 근원을 알고 싶으면 항상 MDN을 참조하면 된다.
구글에 javascript dom event mdn
developer.mozilla.org/ko/docs/Web/Events
NDM 문서중에 navigator 이벤트가 있었는데 유저의 온라인, 오프라인 상태의 변화를 감지한다.
function handleOffline(){
console.log("its offline~");
}
window.addEventListener("offline",handleOffline);
#2.7 DOM- if else - Function practice
자바스크립트에서 css 를 가지고 작업하는것. 대다수의 사람들이 좋아하지 않는다.
HTML 은 HTML 에서만 CSS 는 CSS 에서만 하는것을 선호한다.
<!DOCTYPE html>
<html>
<head>
<title>Something</title>
</head>
<link rel="stylesheet" href="index.css"/>
<body>
<h1 id="title">
This works!
</h1>
<script src="index.js"></script >
</body>
</html>
const title = document.querySelector("#title");
const CLICKED_CLASS = "clicked";
function handleClick(){
const currentClass = title.className;
if(currentClass != CLICKED_CLASS){
title.className = CLICKED_CLASS;
}else{
title.className = "";
}
}
function init() {
title.addEventListener("click", handleClick);
}
init();
body {
background-color: #ecf0f1;
}
h1{
color:#34495e;
transition: color 0.5s ease-in-out;
}
.clicked{
color : #7f8c8d;
}
! 그런데 만약
"<h1 id="title" class ="btn">
This works!
</h1> "
기존에 class 를 가지고 있다면? 이벤트가 발생한 순간 기존의 class 속성 "btn" 은 사라지게 된다. 기존의 속성이 무시되기 때문에 약간의 문제가 있다.
이를 위해 MDN classList 를 사용한다. 클래스를 리스트로 관리한다.
<수정한 JS 코드>
const title = document.querySelector("#title");
const CLICKED_CLASS = "clicked";
function handleClick(){
const hassClass = title.classList.contains(CLICKED_CLASS);
if(!hassClass){
title.classList.add(CLICKED_CLASS);
}else{
title.classList.remove(CLICKED_CLASS);
}
}
function init() {
title.addEventListener("click", handleClick);
}
init();
*class List 참고*
developer.mozilla.org/ko/docs/Web/API/Element/classList
그런데 JS 코드가 너무 길다. Toggle 로 해결 가능하다. Toggle 은 우리가 했던 일들을 반복해준다. 그리고 요약해준다.
const title = document.querySelector("#title");
const CLICKED_CLASS = "clicked";
function handleClick(){
title.classList.toggle(CLICKED_CLASS);
function init() {
title.addEventListener("click", handleClick);
}
init();
이렇게 간단히 수정해도 위 코드와 똑같은 이벤트가 발생한다.
토글.. 다시 봐야지..
'Java Script, HTML, CSS' 카테고리의 다른 글
[Vue] 실행 모드(운영/개발)와 환경 변수 분리하기 (0) | 2022.04.21 |
---|---|
[클론코딩 요약/노마드코더] 바닐라 JS로 크롬 앱 만들기 - #1 THEORY (0) | 2021.02.04 |
자바스크립트 데이터 타입 정리 (0) | 2021.01.10 |
CSS, HTML - gradient 색상 코드 사이트 (유용한 사이트) (0) | 2020.07.21 |
FontAwesome 이용하여 HTML Icon 추가하기 (0) | 2019.11.03 |