Reset.css

브라우저의 기본 스타일 초기화 하는 CND


<!-- css  -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/reset-css@5.0.1/reset.min.css" />
        
        

파비콘(Favicon)

웹페이지를 나타내는 아이콘, 웹페이지의 로고를 설정합니다.

  • favicon.ico : 64 x 64 (px) 또는 32 x 32 또는 16 x 16
  • favicon.png : 500 x 500 (px)
  • iconifier.net 여기서 간편하게 제작 가능
  • icoconverter 여기서 간편하게 제작 가능

<!-- ico -->
<link rel="shortcut icon" href="./resources/ico/favicon.ico" type="image/x-icon" />
<link rel="apple-touch-icon" href="./resources/ico/apple-touch-icon.png" />
<link rel="apple-touch-icon" sizes="57x57" href="./resources/ico/apple-touch-icon-57x57.png" />
<link rel="apple-touch-icon" sizes="72x72" href="./resources/ico/apple-touch-icon-72x72.png" />
<link rel="apple-touch-icon" sizes="76x76" href="./resources/ico/apple-touch-icon-76x76.png" />
<link rel="apple-touch-icon" sizes="114x114" href="./resources/ico/apple-touch-icon-114x114.png" />
<link rel="apple-touch-icon" sizes="120x120" href="./resources/ico/apple-touch-icon-120x120.png" />
<link rel="apple-touch-icon" sizes="144x144" href="./resources/ico/apple-touch-icon-144x144.png" />
<link rel="apple-touch-icon" sizes="152x152" href="./resources/ico/apple-touch-icon-152x152.png" />
<link rel="apple-touch-icon" sizes="180x180" href="./resources/ico/apple-touch-icon-180x180.png" />
        
        

오픈 그래프(The Open Graph protocol)

웹페이지가 소셜 미디어(페이스북 등)로 공유될 때 우선적으로 활용되는 정보를 지정합니다.

og
  • og:type : 페이지의 유형
  • og:site_name : 속한 사이트의 이름
  • og:title : 페이지의 이름(제목)
  • og:description : 페이지의 간단한 설명
  • og:image : 페이지의 대표 이미지 주소(URL)
  • og:url : 페이지 주소(URL)

<!-- og  -->
<meta property="og:type" content="website" />
<meta property="og:site_name" content="jjgodcom" />
<meta property="og:title" content="jjgodcom" />
<meta property="og:description" content="jjgodcom의 프론트 백앤드 정보 정리 사이트 입니다." />
<meta property="og:image" content="./resources/ico/apple-touch-icon-120x120.png" />
<meta property="og:url" content="http://jjgodcom.com/" />
        
        

트위터 카드(Twitter Cards)

웹페이지가 소셜 미디어(트위터)로 공유될 때 우선적으로 활용되는 정보를 지정합니다.

  • twitter:card : 페이지(카드)의 유형
  • twitter:site : 속한 사이트의 이름
  • twitter:title : 페이지의 이름(제목)
  • twitter:description : 페이지의 간단한 설명
  • twitter:image : 페이지의 대표 이미지 주소(URL)
  • twitter:url : 페이지 주소(URL)

<!-- twitter -->
<meta property="twitter:card" content="summary" />
<meta property="twitter:site" content="jjgodcom" />
<meta property="twitter:title" content="jjgodcom" />
<meta property="twitter:description" content="jjgodcom의 프론트 백앤드 정보 정리 사이트 입니다." />
<meta property="twitter:image" content="./resources/ico/apple-touch-icon-120x120.png" />
<meta property="twitter:url" content="http://jjgodcom.com/" />
        
        

Google Fonts

Google Fonts 해당 링크는 구글에서 제공하는 무료 폰트


<!-- web font -->
<link rel="preconnect" href="https://fonts.gstatic.com" />
<link href="https://fonts.googleapis.com/css2?family=Nanum+Gothic:wght@400;700&display=swap" rel="stylesheet" />
<style>
body {
	font-family: 'Nanum Gothic', sans-serif;
}
</style>  
        
        

Google Material Icons

Google Material Icons 해당 링크는 기본 아이콘 무료 제공


<!-- IN HEAD -->
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" />

<!-- IN BODY -->
<div> class="material-icons">upload</div>
        
        

BEM(Block Element Modifier)

HTML 클래스 속성의 작명법

  • 요소__일부분 : Underscore(Lodash) 기호로 요소의 일부분을 표시
  • 요소—상태 : Hyphen(Dash) 기호로 요소의 상태를 표시

<!-- 요소의 일부분 -->
<div class="container">
  <div class="container__name"></div>
  <div class="item">
    <div class="item__name"></div>
  </div>
</div>

<!-- 요소의 상태 -->
<div class="btn btn--primary"></div>
<div class="btn btn--success"></div>
<div class="btn btn--error"></div>
        
        

BootStrap

부트스트랩 (5.0버전 사용하기)

CDN 프로젝트 생성


<!-- css -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css">

<!-- js -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js"></script>
        

NPM 프로젝트 생성


npm init -y
npm install parcel-bundler -D
npm install bootstrap@5.0.0

package.json 수정
"scripts": {
    "dev": "parcel index.html",
    "build": "parcel build index.html"
  },
  npm run dev 끝
        

main.scss


// css 파일 연결
@import "../node_modules/bootstrap/scss/bootstrap.scss"
        

main.js


// bootstrap js파일 연결
import bootstrap from 'bootstrap/dist/js/bootstrap.bundle';
        

Lodash

Lodash는 다양한 유틸리티 기능을 제공하는 자바스크립트 라이브러리입니다.


<script> src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>
<script>>
  // _.throttle 기능을 사용해서 스크롤할때 과부화 없이 0.3초마다 실행되게 함
  // _.throttle(함수, 시간)
  window.addEventListener("scroll", _.throttle(function () {
    console.log("scroll");
  }, 300));
</script>
        
        

uniq

  • _.uniqBy() : 중복이 발생한 배열에서 쓰면 중복 제거후 배열 생성
  • _.unionBy() : 배열을 합치기 전이라면 인수로 적용후 새로운 배열로 생성

import _ from 'lodash'; // From 'node_modules'

const usersA = [
  { userId : "1" , name: "JJGODCOM"},
  { userId : "2" , name: "Neo"},
];
const usersB = [
  { userId : "1" , name: "JJGODCOM"},
  { userId : "3" , name: "Amy"},
];
// 배열이 합쳐져 있고 중복값이 있을때 좋음
const usersC = usersA.concat(usersB);
console.log("concat", usersC);
console.log("uniqBy", _.uniqBy(usersC, "userId"));

// _.unionBy : 배열이 여러개일때 사용
const usersD = _.unionBy(usersA, usersB, "userId");
console.log("unionBy", usersD);
        

find

  • _.find() : 배열에서 원하는 객체 찾기
  • _.findIndex() : 배열 index번호 찾기
  • _.remove() : `_.remove` : 배열에서 원하는 객체 삭제

import _ from 'lodash'; // From 'node_modules'

const users = [
  { userId : "1" , name: "JJGODCOM"},
  { userId : "2" , name: "Neo"},
  { userId : "3" , name: "Amy"},
  { userId : "4" , name: "Evan"},
  { userId : "5" , name: "Lewis"},
];

const foundUser = _.find(users, {name:"Amy"});
const foundUserIndex = _.findIndex(users, {name:"Amy"});
console.log(foundUser);
console.log(foundUserIndex);

_.remove(users, {name:"JJGODCOM"});
console.log(users);
        

GSAP & ScrollToPlugin

GSAP(The GreenSock Animation Platform)은 자바스크립트로 제어하는 타임라인 기반의 애니메이션 라이브러리입니다.

ScrollToPlugin은 스크롤 애니메이션을 지원하는 GSAP 플러그인입니다.


<!-- gsap -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.5.1/gsap.min.js" integrity="sha512-IQLehpLoVS4fNzl7IfH8Iowfm5+RiMGtHykgZJl9AWMgqx0AmJ6cRWcB+GaGVtIsnC4voMfm8f2vwtY+6oPjpQ==" crossorigin="anonymous"></script>
<!-- ScrollToPlugin -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.5.1/ScrollToPlugin.min.js" integrity="sha512-nTHzMQK7lwWt8nL4KF6DhwLHluv6dVq/hNnj2PBN0xMl2KaMm1PM02csx57mmToPAodHmPsipoERRNn4pG7f+Q==" crossorigin="anonymous"></script>
        
        

forEach 예시


fadeEls.forEach(function (fadeEl, index) {
  gsap.to(fadeEl, 1, {
    delay : (index + 1) * 0.7 , // index 값에 따라 순차적으로 나오게 함
    opacity : 1
  });
});
        
        

램덤 함수를 이용한 예시


// 램덤함수를 이용하여 애니매이션 만들기
// 범위 랜덤 함수(소수점 2자리까지)
function random(min, max) {
  // `.toFixed()`를 통해 반환된 문자 데이터를,
  // `parseFloat()`을 통해 소수점을 가지는 숫자 데이터로 변환
  return parseFloat((Math.random() * (max - min) + min).toFixed(2))
}
// youtube__area animation
function floatingObject(selector, delay, size) {
  // gsap.to(요소, 애니메이션 동작 시간, 옵션);
  gsap.to(selector, random(1.5, 2.5), {
    y: size, // y축
    repeat: -1, // 무한
    yoyo: true,
    ease: Power1.easeInOut, // 움직임 부드러워짐
    delay: random(0, delay) // 지연시간
  });
}
floatingObject(".floating1", 1, 15);
        
        

스트롤 최상단 이동 버튼


const toTopEl = document.querySelector("#to-top");

toTopEl.addEventListener("click", function () {
  gsap.to(window, 0.7, {
    scrollTo: 0
  });
});
        
        

ScrollMagic

ScrollMagic은 스크롤과 요소의 상호 작용을 위한 자바스크립트 라이브러리입니다.

  • 대표적으로 어떤 요소가 현재 화면에 보이는 상태인지를 확인할 때 사용합니다.
  • ScrollMagic API

<script> src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.8/ScrollM>agic.min.js"></script>
        
        

기본 예제


new ScrollMagic
  .Scene({ // 감시할 장면(Scene)을 추가
    triggerElement: spyEl, // 보여짐 여부를 감시할 요소를 지정
    triggerHook: .8 // 화면의 80% 지점에서 보여짐 여부 감시
  })
  .setClassToggle(spyEl, 'show') // 요소가 화면에 보이면 show 클래스 추가
  .addTo(new ScrollMagic.Controller()) // 컨트롤러에 장면을 할당(필수!)
        
        

Swiper

Swiper는 하드웨어 가속 전환과 여러 기본 동작을 갖춘 현대적인 슬라이드 라이브러리입니다.

HTML


<!-- in HEAD -->
<link rel="stylesheet" href="https://unpkg.com/swiper@6.8.4/swiper-bundle.min.css" />
<script src="https://unpkg.com/swiper@6.8.4/swiper-bundle.min.js"></script>

<!-- in BODY -->
<div class="swiper-container">
  <div class="swiper-wrapper">
    <div class="swiper-slide">1</div>
    <div class="swiper-slide">2</div>
    <div class="swiper-slide">3</div>
  </div>
</div>

<!-- pagination-->
<div class="swiper-pagination"></div>

<!-- btn-->
<div class="swiper-prev"></div>
<div class="swiper-next"></div>
        
        

기본 예제


//new Swiper(요소, 옵션);
new Swiper('.swiper-container', {
  direction: 'vertical', // 수직 슬라이드
  autoplay: true, // 자동 재생 여부
	autoplay : { // 옵션 추가
    delay: 5000 // 5s
  }
  loop: true, // 반복 재생 여부
	slidesPerView: 3, // 한 번에 보여줄 슬라이드 개수
  spaceBetween: 10, // 슬라이드 사이 여백
  centeredSlides: true, // 1번 슬라이드가 가운데 보이기
	slidesPerView: 5 // 한화면에 몇개 보여줄건지
	pagination: { // 페이지 번호 사용 여부
	  el: '.promotion .swiper-pagination', // 페이지 번호 요소 선택자
    clickable: true // 사용자의 페이지 번호 요소 제어 가능 여부
  },
  navigation: { // 슬라이드 이전/다음 버튼 사용 여부
    prevEl: '.promotion .swiper-prev', // 이전 버튼 선택자
    nextEl: '.promotion .swiper-next' // 다음 버튼 선택자
  }
});
        
        

Youtube API

IFrame Player API 를 통해 YouTube 동영상을 제어할 수 있습니다.

플레이어 매개변수(playerVars) 에서 더 많은 옵션을 확인할 수 있습니다.


<!-- in HEAD -->
<script> defer src="./js/youtube.js"></script>

<!-- in BODY -->
<div> id="player"></div>
        
        

기본 예제


// Youtube IFrame API를 비동기로 로드합니다.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

function onYouTubePlayerAPIReady() {
  // <div id="player"></div>
  // 아래 플레이어는 자동으로 아이디 player 찾음 #절대 넣지마셈
  new YT.Player('player', {
    videoId: 'An6LvWQuj_8', // 재생할 유튜브 영상 ID
    playerVars: {
      autoplay: true, // 자동 재생 유무
      loop: true, // 반복 재생 유무
      playlist: 'An6LvWQuj_8' // 반복 재생할 유튜브 영상 ID 목록
    },
    events: {
      // 영상이 준비되었을 때,
      onReady: function (event) {
        event.target.mute(); // 음소거!
      }
    }
  });
}
        
        

OMDB API

OMDB API 는 오픈 무비 데이터베이스 입니다.

axios

OMDB API를 사용하기 위해서는 편리한 axios 사용을 합니당

터미널에서 npm i axios 설치


import axios from "axios";

function fetchMovies() {
  axios
    .get("https://www.omdbapi.com/?apikey=7035c60c&s=frozen")
    .then(res => {
      console.log(res);
      const h1El = document.querySelector("h1");
      const imgEl = document.querySelector("img");
      h1El.textContent = res.data.Search[0].Title;
      imgEl.src = res.data.Search[0].Poster;
    });
}
fetchMovies();
        
        

node.js 배포

여기 보고 참고

약속

  • html 태그 네이밍 : menu-logo
  • js 네이밍 : 카멜케이스로 foundUser

유용한 CSS

16:9 비율


/* 100% : 56.25% = 16 : 9 */

width : 100%
padding-top : 56.25%
        
        

가운데 배치


transform:translateX(-50%); // left: 50%;
transform:translateY(-50%); // top: 50%;
transform:translate(-50%,-50%); // top: 50%; left: 50%;
        
        

텍스트 ... 처리


.ellipsis{
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
        
        

자주쓰는 JS

show, hide()


let flag = false;

element.addEventListener("click", function () {
  flag = !flas // 반대값으으로 변경
  if(flag){
    // 숨김 처리
    el.classList.add("hide");
  }else{
    // 보임 처리
    el.classList.remove("hide");
  }
});
        
        

랜덤한 숫자를 생성하는 함수


// 범위 랜덤 함수(소수점 2자리까지)
function random(min, max) {
  // `.toFixed()`를 통해 반환된 문자 데이터를,
  // `parseFloat()`을 통해 소수점을 가지는 숫자 데이터로 변환
  return parseFloat((Math.random() * (max - min) + min).toFixed(2))
}