📝
서은 STUDY_SCRIPT
  • JAVASCRIPT 기록
  • JAVASCRIPT 문법정리
    • 데이터 저장하기
    • 데이터 불러오기
    • 데이터 실행하기
    • 데이터 제어하기
    • 면접질문 정리
  • PHP를 이용한 사이트 작업
    • PHP와 MySQL
      • 댓글쓰기
      • 회원가입
      • 로그인
      • 게시판
        • 페이지네이션 & 게시글보기
        • 수정/삭제/목록/검색
  • 생활코딩 JavaScript
    • JavaScript 입문수업
      • Basic
        • 자바스크립트 기본 세팅
        • 데이터타입
        • 변수
        • 연산자
        • 조건문
        • 반복문
        • 함수
        • 배열
        • 객체
        • 모듈
        • 정규표현식
      • 함수지향
        • 유효범위
        • 값으로서 함수
        • 값으로서 콜백
        • 클로저
        • arguments
        • 함수의 호출
      • 객체지향
        • 생성자와 new
        • 전역객체
        • this
        • 상속
        • Prototype
        • 표준내장객체의 확장
        • Object
        • 데이터 타입
        • 복제 & 참조
    • JavaScript Basic
      • 자바스크립트란?
      • 데이터타입
      • 변수와 대입연산자
      • 제어할 태그 선택
      • 비교연산자와 불리언
      • 조건문 if
      • 리팩토링
      • 배열 [ ]
      • 반복문 while
      • 배열과 반복문
        • 배열과 반복문의 활용
      • 함수
        • 함수의 활용
      • 객체 { }
        • 객체와 반복문 for~in
        • 프로퍼티와 메소드
        • 객체의 활용
      • 파일로 쪼개서 정리정돈
      • 라이브러리 & 프레임워크
      • UI & API
    • Web Browser
      • JavaScript란?
      • BOM
        • 전역객체 window
        • 사용자와 커뮤니케이션
        • Location 객체
        • Navigator 객체
        • 창 제어
      • DOM
        • 제어 대상 찾기
        • jQuery
        • HTMLElement
        • Element 객체
          • 식별자 API
          • 조회 API
          • 속성 API
        • Node 객체
          • Node 관계 API
          • Node 종류 API
          • Node 변경 API
          • jQuery 노드 변경 API
          • 문자열로 노드 제어
        • HTMLCollection
      • 이벤트
        • 이벤트 등록
        • 이벤트 전파(버블링과 캡처링)
        • 이벤트 기본 동작 취소
        • 이벤트 타입
      • 네트워크 통신
        • Ajax
        • JSON
  • NOMAD JAVASCRIPT
    • VanillaJS
      • Why JS?
      • ES5, ES6
      • Basic
        • Alert & Console
        • Variable
        • Data Types
        • Array & Object
      • Function
      • DOM
        • Event & Event handler
        • Conditional
        • Function Practice
      • Momentum App
        • Making a JS Clock
        • Saving the User Name
        • To-Do List
        • Image Background
        • Getting Weather
  • DREAM CODING
    • 자바스크립트 기초 강의 (ES5+)
      • JavaScript 역사
      • async & defer / Strict Mode
      • Variable / Hoisting / Data Type
      • Operator / if / Loop
      • Function
        • 함수의 선언
        • 함수의 표현
      • Class
      • Object
      • Array
      • Array API
      • JSON
      • Callback
      • Promise
      • Async & Await
  • WEB BOS
    • #JavaScript30
Powered by GitBook
On this page
  • 1. DOM과 조건문 (if~else)
  • 1-1. JS코드만으로 Style과 클릭변경 효과주기
  • 1-2. CSS에 Style을 주어 JS코드 깔끔히 정리
  • 1-3. 토글함수를 이용한 가장 깔끔한 코드
  • 2. Online / Offline (와이파이 껐다 켜기)

Was this helpful?

  1. NOMAD JAVASCRIPT
  2. VanillaJS
  3. DOM

Function Practice

1. DOM과 조건문 (if~else)

1-1. JS코드만으로 Style과 클릭변경 효과주기

const title = document.querySelector("#title");

const BASE_COLOR = "rgb(52, 73, 94)";
const OTHER_COLOR = "red";

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("click", handleClick); //원할 때 handleClick 호출
}

init(); //타이틀을 클릭할 때 마다 회색-빨강 교차적으로 글색상이 변경됨

1-2. CSS에 Style을 주어 JS코드 깔끔히 정리

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 = ""; //Blank
  }
}

function init(){
  title.addEventListener("click", handleClick);
}

init(); //타이틀을 클릭할 때 마다 회색-진회색 0.5초씩 교차적으로 글색상이 변경됨
<!DOCTYPE html>
<html>
  <head>
    <title>Something</title>
    <link rel="stylesheet" href="index.css" />
  </head>
  <body>
      <h1 id="title" class="clicked">This works!</h1>
      <script src="index.js"></script>
  </body>
</html>
}

h1{
    color:#34495e;
    transition:color .5s ease-in-out;
}

.clicked{
    color:#7f8c8d;
}

1-3. 토글함수를 이용한 가장 깔끔한 코드

const title = document.querySelector("#title");

const CLICKED_CLASS = "clicked";

function handleClick(){
  title.classList.toggle(CLICKED_CLASS);
}

function init(){
  title.addEventListener("click", handleClick);
}

init();
const title = document.querySelector("#title");

const CLICKED_CLASS = "clicked";

function handleClick(){
  const hasClass = title.classList.contains(CLICKED_CLASS);
  if (hasClass){
    title.classList.remove(CLICKED_CLASS);
  } else {
    title.classList.add(CLICKED_CLASS);
  }
}

function init(){
  title.addEventListener("click", handleClick);
}

init();
<!DOCTYPE html>
<html>
  <head>
    <title>Something</title>
    <link rel="stylesheet" href="index.css" />
  </head>
  <body>
      <h1 id="title" class="btn">This works!</h1>
      <script src="index.js"></script>
  </body>
</html>
body {
    background-color:#ecf0f1;
}

.btn{
    cursor:pointer;
}

h1{
    color:#34495e;
    transition:color .5s ease-in-out;
}

.clicked{
    color:#7f8c8d;
}

toggle 함수를 이용하여 깔끔한 코드로 클릭 반복 가능

2. Online / Offline (와이파이 껐다 켜기)

search : javascript dom event mdn

function handleOffline(){
    console.log("Byebye");
}
 
function handleOnline(){
    console.log("Welcome back");
}
 
function init(){
    window.addEventListener("offline", handleOffline);
    window.addEventListener("online", handleOnline);
}
init();
PreviousConditionalNextMomentum App

Last updated 3 years ago

Was this helpful?

Flat UI Colors 2 - 14 Color Palettes, 280 colors 🎨
Logo