내장함수
const B' = A.querySelector(B) ; A에서 B의 요소 하나 찾기
const B' = A.querySelectorAll(B) ; A에서 B의 요소 모두 찾기
A.addEventListener('click',B()) ; A클릭 시 B실행
A.classList.add('B') ; A요소의 클래스명에 'B' 추가 / add, remove, contains
A'=document.createElement(A) ; A'라는 의름의 A태그의 요소 생성
A.appendChild(B) ; A의 자식요소로 B 삽입
A.forEach(function(B,index){} ; A내의 요소들이 하나씩 B에 들어가며, index는 0부터 1씩 증가함
A.textContent ; A의 내용 참조
A.src ; A의 src속성 변경
실제 활용
클릭 시 .focus 추가, 클릭 해제 시 .focus 제거
더보기
const searchEl = document.querySelector('.search'); //HTMl에서 .search 찾기
const searchInputEl = searchEl.querySelector('input'); //searchEl, 즉 .search에서 input찾기
searchEl.addEventListener('click', function () { //searchEl 클릭 시 searchInputEl에 클릭한 것과 같은 효과
searchInputEl.focus();
});
searchInputEl.addEventListener('focus', function () { //클릭 시
searchEl.classList.add('focused');
searchInputEl.setAttribute('placeholder', '통합검색');
});
searchInputEl.addEventListener('blur', function () { //클릭 해제 시
searchEl.classList.remove('focused');
searchInputEl.setAttribute('placeholder', '');
});
CSS요소
.search input:focus{
width: 190px;
border-color: #669900;
}
일정 스크롤 이상 시 사라짐(gsap라이브러리, throttle 라이브러리 사용)
더보기
const badgeEl = document.querySelector('header .badges');
window.addEventListener('scroll', _.throttle(function () {
if (window.scrollY > 500) {
gsap.to(badgeEl, .6, {
opacity: 0,
display: 'none'
});
} else {
gsap.to(badgeEl, .6, {
opacity: 1,
display: 'block'
});
}
}, 300));
throttle ; 콜백 함수를 지정한 시간 내 한번만 호출됨 (scroll과 같이 굉장히 짧은 시간에 많은 이벤트 발생하는 경우 사용)
_.throttle(함수, 시간);
GSAP(GreenSock Animation Platform) ; 애니메이션을 통해 세세한 동작들을 만들 수 있음
gsap.to(요소, 지속시간, 옵션);
하나씩 나타나게 하기
더보기
const fadeEls = document.querySelectorAll('.visual .fade-in')
fadeEls.forEach(function (fadeEl, index) { //fadeEls의 개수만큼 실행
gsap.to(fadeEl, 1, {
delay: (index + 1) * .7, //0.7,1.4,2.1,2.8..
opacity: 1
})
});
CSS 요소
.fade-in{
opacity:0;
}
자동 swiper(Swiper라이브러리 사용) - 수직
더보기
// new Swiper(선택자,옵션)
new Swiper('.notice-line .swiper-container',{
direction:'vertical',
autoplay:true,
loop:true
});
HTML 요소
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide">
<a href="javascript:void(0)">크리스마스 & 연말연시 스타벅스 매장 영업시간 변경 안내</a>
</div>
<div class="swiper-slide">
<a href="javascript:void(0)">[당첨자 발표] 2021 스타벅스 플래너 영수증 이벤트</a>
</div>
<div class="swiper-slide">
<a href="javascript:void(0)">스타벅스커피 코리아 애플리케이션 버전 업데이트 안내</a>
</div>
<div class="swiper-slide">
<a href="javascript:void(0)">[당첨자 발표] 뉴이어 전자영수증 이벤트</a>
</div>
</div>
<a href="javascript:void(0)" class="notice-line__more">
<div class="material-icons">add_circle</div>
</a>
</div>
자동 swiper(Swiper라이브러리 사용) - 수평
더보기
new Swiper('.promotion .swiper-container',{
// direction:'horizontal', ; 기본값
slidesPerView:3, // 한번에 보여줄 슬라이드 개수
spaceBetween:10, // 슬라이드 사이 여백
centeredSlides:true, //1번 슬라이드가 가운데 보이기
loop:true,
autoplay:{
delay:5000
}
pagination:{
el:'.promotion .swiper-pagination', //페이지 번호 요소 선택자
clickable : true //사용자의 페이지 번호 요소 제어 가능 여부
},
navigation:{
prevEl:'.promotion .swiper-prev',
nextEl:'.promotion .swiper-next'
}
});
HTML 요소
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide">
<img src="./images/promotion_slide1.jpg" alt="2021 뉴이어, 스타벅스와 함께 즐겁고 활기차게 시작하세요!" />
<a href="javascript:void(0)" class="btn">자세히 보기</a>
</div>
<div class="swiper-slide">
<img src="./images/promotion_slide2.jpg" alt="기간 내 스타벅스 카드 e-Gift를 3만원 이상 선물 시, 아메리카노 e-쿠폰을 드립니다." />
<a href="javascript:void(0)" class="btn">자세히 보기</a>
</div>
<div class="swiper-slide">
<img src="./images/promotion_slide3.jpg" alt="뉴이어 푸드와 제조 음료를 세트로 구매 시, 뉴이어 음료 BOGO(1+1) 쿠폰을 드립니다." />
<a href="javascript:void(0)" class="btn">자세히 보기</a>
</div>
<div class="swiper-slide">
<img src="./images/promotion_slide4.jpg" alt="신년 MD 상품 포함 3만원 이상 구매 고객께 아메리카노(톨사이즈) 쿠폰을 드립니다." />
<a href="javascript:void(0)" class="btn">자세히 보기</a>
</div>
<div class="swiper-slide">
<img src="./images/promotion_slide5.jpg" alt="2017 DIGITAL LUCKY DRAW 100% 당첨의 행운을 드립니다!" />
<a href="javascript:void(0)" class="btn">자세히 보기</a>
</div>
</div>
</div>
클릭하면 사라지고, 클릭하면 나타나는 버튼
더보기
const promotionEl= document.querySelector('.promotion');
const promotionToggleBtn= document.querySelector('.toggle-promotion');
let isHidePromotion = false;
promotionToggleBtn.addEventListener('click',function(){
isHidePromotion=!isHidePromotion
if(isHidePromotion){
// gsap.to(요소, 지속시간, 옵션)
promotionEl.classList.add('hide');
}else{
promotionEl.classList.remove('hide');
}
});
promotionToggleBtn=false이면 안나타남 ; classList.add('hide')로 class명에 hide추가
promotionToggleBtn=true이면 나타남 ; classList.remove('hide')로 class명에 hide제거
CSS요소
.notice .promotion{
// 설정값
transition:height .4s;
overflow:hidden; //넘치는걸 제거해야 내용도 height:0인것에 맞춰짐
}
.notice .promotion.hide{
height: 0;
}
풍선처럼 둥둥 띄우기
더보기
// 범위 랜덤 함수(소수점 2자리까지)
function random(min, max) {
// `.toFixed()`를 통해 반환된 문자 데이터를,
// `parseFloat()`을 통해 소수점을 가지는 숫자 데이터로 변환
return parseFloat((Math.random() * (max - min) + min).toFixed(2))
}
function floatingObject(selector, delay, size) {
// gsap.to(요소, 시간, 옵션);
gsap.to(
selector, //선택자
random(1.5, 2.5), //애니메이션 동작 시간
{ // 옵션
y: size,
repeat: -1, // 무한 반복
yoyo: true, // 1번실행 후 반대로 실행
ease: Power1.easeInOut, //gsap easing에서 가져옴
delay: random(0, delay)
}
);
}
floatingObject('.floating1', 1, 15);
floatingObject('.floating2', .5, 15);
floatingObject('.floating3', 1.5, 20);
특정 스크롤 넘으면 동작
더보기
const spyEls = document.querySelectorAll('section.scroll-spy');
spyEls.forEach(function (spyEl) {
//Scene ; ScrollMagic을 통해 특정한 요소를 감시하는 옵션을 지정하는 메소드
new ScrollMagic
.Scene({
triggerElement: spyEl, //보여짐 여부를 감시할 요소를 지정
triggerHook: .8 //뷰포트의 0.8지점에 그 요소가 걸리면 setClassToggle 실행
})
.setClassToggle(spyEl, 'show')
.addTo(new ScrollMagic.Controller());
});
이번 연도 가져와서 출력
더보기
const thisYear = document.querySelector('.this-year');
thisYear.textContent = new Date().getFullYear();
클릭시 맨 위로 올라감
더보기
toTopEl.addEventListener('click',function(){
gsap.to(window,.7,{
scrollTo:0
});
});
유튜브 클립 추가
더보기
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
function onYouTubeIframeAPIReady() {
new YT.Player('player', { //player는 #player
videoId: 'An6LvWQuj_8', //최초 재생할 유튜브 영상 ID
playerVars:{
autoplay:true,
loop:true,
videoId: 'An6LvWQuj_8' //반복재생할 유튜브 영상 ID
},
events:{
onReady:function(event){ // 영상이 준비가 되면
event.target.mute() // 음소거
}
}
});
}
'WebProgramming > JS' 카테고리의 다른 글
[JS] 원시 데이터, 참조형 데이터 / 얕은 복사와 깊은 복사 (0) | 2022.06.11 |
---|---|
[JS] 메소드(String, Math, Array, Object) (0) | 2022.06.10 |
[JS] 생성자 함수(Prototype), Class 상속 (0) | 2022.06.06 |
[JS] 함수 (0) | 2022.06.04 |
[웹 프로그래밍] JS 작성 툴 (Node.js, NVM, NPM) (0) | 2022.06.04 |
[JS] JavaScript 기본 문법 / 표기법, 데이터 종류, 변수 (0) | 2022.05.26 |
[JavaScript] 객체, 상속 (0) | 2022.05.15 |
JavaScript 기본 문법 (0) | 2022.05.06 |