jquery - HTML의 DOM 조작과 이벤트 제어, 애니메이션과 Ajax 등 웹 화면을 다루는 자바스크립트 라이브러리
jQuery가 가진 철학 – write less, do more
jQuery가 제공하는 기능 • CSS 조작 • HTML DOM 조작과 이벤트 처리 • 애니메이션 효과 • AJAX 처리방식을 편리하게 사용 • Utilities
</ head >
< body >
< p > 클릭하면 없어짐 </ p >
< p > 클릭하면 없어짐 </ p >
< p > 클릭하면 없어짐 </ p >
< script >
$ ( function () {
$ ( "p" ). click ( function () {
$ ( this ). hide ();
});
});
</ script >
Javascript var titleElements = document.getElementsByClassName("title"); for (var titleElement in titleElements) { titleElement.className = titleElement.className + " selected"; }
▪ JQuery $(".title").addClass("selected"); >> 적은 양의 코드로 동일한 동작을 할 수 있음
+ 간단하게 화면을 구성해서 사용하는 소규모 프로젝트에서는 확장가능한 자바스크립트 라이브러리이다.
jquery 사용하
Npm 이나 yarn 패키지 추가 명령어를 사용 ➢ npm install jquery ➢ yarn add jquery
jQuery library를 jQuery.com 에서 다운로드 받아 사용하기 ▪ 동일 폴더에 있는 경우 상대경로만 적어서 사용가능
jQuery 를 CDN을 통해 다운로드나 설치 없이 사용하는 방법 • CDN은 사용자에게 간편하게 콘텐츠를 제공하는 방식 jquery 기본문법
▪ jQuery를 이용해 (query) HTML 요소를 선택하고 , ( selector) 선택된 요소에 "actions" 을 수행
>> $(selector).action()
• $ sign 은 jQuery 정의와 접근을 의미 • (selector) 는 HTML elements 를 "query (or 검색)" • jQuery action() element(s) 에 수행되는 동작을 의미
ex)
$(this).hide() - 현재 element 를 숨긴다. $("p").hide() - 모든 <p> elements 를 숨긴다. $(".test").hide() - class가 "test"인 모든 요소를 숨긴다. $("#test").hide() - id가 "test"인 모든 요소를 숨긴다.
< body >
< button id = "btn" > 버튼을 클릭하면 모두 없어짐 </ button >
< p > 클릭하면 없어짐 </ p >
< p > 클릭하면 없어짐 </ p >
< p > 클릭하면 없어짐 </ p >
< script >
$ ( () => {
$ ( "#btn" ). click (() => {
$ ( "p" ). hide ();
})
});
</ script >
jquery 객체
$함수 활용
$ 함수의 매개 변수에는 문서 객체, CSS 형식, HTML 형식의 문자열 삽입
>>$(매개변수).메소드(매개변수,매개변수)
보통 css 선택자로 jquery 객체 생성함 > $('h1');
▪ jQuery 메서드를 document ready event안에서 사용
$(document).ready(function(){ // jQuery methods go here... });
Document로딩이 끝나기 전에(document ready 전에) 어떤 jQuery코드라도 사용되는 것을 막기 위함
jquery selectors
element selector
$(document).ready(function(){ $("button").click(function(){ $("p").hide(); }); });
h1 태그에 parent ( ) 메소드와 find ( ) 메소드를 사용
h1의 부모 태그 선택 > $('h1').parent()
h1 태그 내부의 i 태그 선택 > $('h1').find('i')
< body >
< h1 > 제목1 </ h1 >
< h1 > 제목2 </ h1 >
< h1 > 제목3 </ h1 >
< h1 > 제목4 </ h1 >
< h1 > 제목5 </ h1 >
< h1 > 제목6 </ h1 >
< script >
$ ( document ). ready ( function () {
const headerList = $ ( "h1" );
for ( let i = 0 ; i < headerList . length ; i ++) {
const header = headerList . get ( i );
if ( i % 2 == 1 ) {
$ ( header ). css ( "backgroundColor" , "red" ). css ( "color" , "white" );
}
}
});
</ script >
each() - 선택한 문서 객체에 반복 적용 >>for ()문
Array 객체의 forEach ( )메소드와 인덱스, 요소 순서가 다름
>> $('h1').each(fumction (index, item) { } );
$ ( document ). ready ( function () {
const headerList = $ ( "h1" );
$ ( headerList ). each (( i , header ) => {
if ( i % 2 == 1 ) {
$ ( header )
. css ( "backgroundColor" , "red" )
. css ( "color" , "white" );
}
})
});
>>
$ ( document ). ready ( function () {
$ ( 'h1' ). each (( i , header ) => {
if ( i % 2 == 1 ) {
$ ( header )
. css ( "backgroundColor" , "red" )
. css ( "color" , "white" );
}
})
});
text() - html 태그 내부의 문자 조작 (innerHTML() )
$ ( document ). ready ( function () {
$ ( 'h1' ). each (( i , header ) => {
if ( i % 2 == 1 ) {
$ ( header )
. css ( "backgroundColor" , "red" )
. css ( "color" , "white" );
console . log ( $ ( header ). text ());
$ ( header ). text ( "짝수번째 헤더" );
}
})
});
css() - 스타일 조작
< body >
< title > jquery event </ title >
< script >
$ (() => {
for ( let i = 0 ; i < 256 ; i ++) {
$ ( "<div></div>" )
. css ({
height : 2 ,
background : `rgb( ${ i } , ${ i } , ${ i } )` ,
})
. appendTo ( "body" );
}
});
</ script >
</ body >
attr() - 속성 조작
< script >
$ (() => {
$ ( "img" ). each (( i , img ) => {
$ ( "img" ). attr ({
src : "./img/spring.jpg" ,
alt : "spring" ,
width : ( i + 1 ) * 100 ,
height : 100 ,
});
});
});
</ script >
.each() 사용해 너비 (index + 1) * 100인 이미지 만들기
< script >
$ (() => {
$ ( "img" ). each (( i , img ) => {
$ ( "img" ). attr ({
src : "./img/spring.jpg" ,
alt : "spring" ,
width : ( i + 1 ) * 100 ,
height : 100 ,
});
});
});
</ script >
h1 태그 생성해 글자, 속성, 스타일 설정해 body에 추가
< script >
$ (() => {
$ ( "<h1></h1>" ). text ( "appendTo1" ). appendTo ( $ ( ".target" ));
$ ( "<h1></h1>" ). text ( "appendTo2" ). appendTo ( $ ( ".target" ));
$ ( "<h1></h1>" ). text ( "prependTo" ). prependTo ( $ ( ".target" ));
});
</ script >
</ head >
< body >
< div class = "target" ></ div >
</ body >
이벤트 연결 - on()
이벤트 제거 - off()
< script >
$ (() => {
$ ( "h1" ). on ( "click" , () => {
const text = $ ( this ). text ();
alert ( text );
});
});
</ script >
</ head >
< body >
< h1 > header1 </ h1 >
< h1 > header2 </ h1 >
</ body >
이벤트 발생 시 새로운 객체 생성
< script >
$ (() => {
const handler = function ( event ) {
$ ( "<h1></h1>" )
. text ( $ ( event . target ). text ())
. on ( handler )
. appendTo ( "body" );
};
$ ( "h1" ). on ( handler );
});
</ script >
</ head >
< body >
< h1 > header1 </ h1 >
< h1 > header2 </ h1 >
</ body >
에니메이션 - animate()
스타일에 적용
숫자 적용할 수 있는 모든 속성에 사용 가능
콜백 함수는 애니메이션 종료 시 호출(생략 가능)
>$(선택자).animate(속성, 시간, 콜백함수);
< style >
.first {
width : 100px ;
height : 100px ;
background-color : red ;
opacity : 0.3 ;
position : absolute ;
left : 10px ;
top : 50px ;
}
.second {
width : 100px ;
height : 100px ;
background-color : red ;
opacity : 0.3 ;
position : absolute ;
left : 10px ;
top : 200px ;
}
.third {
width : 100px ;
height : 100px ;
background-color : red ;
opacity : 0.3 ;
position : absolute ;
left : 10px ;
top : 350px ;
}
</ style >
< script >
$ (() => {
$ ( "button" ). click (() => {
$ ( ".first" ). animate (
{
left : "500px" ,
opacity : 0.8 ,
},
1000 ,
() => {
alert ( "이동 완료" );
}
);
$ ( ".second" ). animate (
{
left : "500px" ,
opacity : 0.8 ,
},
1000 ,
"swing"
);
$ ( ".third" ). animate (
{
left : "500px" ,
opacity : 0.8 ,
},
1000 ,
"linear"
);
});
});
</ script >
</ head >
< body >
< button > box 이동과 투명도 변경 </ button >
< hr />
< div class = "first" ></ div >
< div class = "second" ></ div >
< div class = "third" ></ div >
</ body >
starbucks animation study
[index.html]
< body >
< header ></ header >
< section id = "fav_wrap" >
< div class = "fav_txt_01" >
< p class = "fav_text big-text" > PICK </ p >
< p class = "fav_text medium-text" > YOUR </ p >
< p class = "fav_text small-text" > FAVORITE </ p >
</ div >
< div class = "fav_txt_02" >
< p class = "fav_text fav_menu" >
다양한 메뉴를 < br /> 스타벅스에서 즐겨보세요
</ p >
</ div >
< img
id = "fav_img"
src = "./img/2025_spring_pick_img.png"
alt = "spring_pick"
/>
</ section >
</ body >
[starbucks.js]
$ (() => {
$ ( window ). scroll (() => {
if ( $ ( window ). scrollTop () > 125 ) {
$ ( ".fav_txt_01" ). css ( "animation" , "move-backward 2s ease forwards" );
$ ( ".fav_txt_02" ). css ( "animation" , "move-backward 2s ease forwards" );
} else {
$ ( ".fav_txt_01" ). css ( "animation" , "move-forward 2s ease forwards" );
$ ( ".fav_txt_02" ). css ( "animation" , "move-forward 2s ease forwards" );
}
});
});
[css]
@charset "utf-8" ;
body {
margin : 0px ;
height : 1600px ;
}
#fav_wrap {
background : url ( "../img/background.png" ) no-repeat fixed ;
position : absolute ;
width : 1280px ;
height : 800px ;
}
#fav_wrap .fav_text {
color : white ;
position : absolute ;
animation : move-forward ws ease-in-out ;
}
.fav_txt_01 {
position : absolute ;
z-index : 1 ; /* 01은 위에 위치하도록 설정 */
left : -200px ; /*초기위치*/
opacity : 0.1 ;
}
.fav_txt_02 {
position : relative ;
z-index : 0 ; /* 02는 아래 위치하도록 설정 */
top : 300px ; /* 원하는 만큼 아래로 내리기 */
left : -200px ; /*초기위치*/
opacity : 0.1 ;
}
#fav_wrap #fav_img {
position : absolute ;
width : 600px ;
height : 400px ;
right : 200px ;
top : 80px ;
}
.big-text {
font-size : 7em ;
top : -100px ;
left : 50px ;
}
.medium-text {
font-size : 4em ;
top : 60px ;
left : 110px ;
}
.small-text {
font-size : 2em ;
top : 180px ;
left : 140px ;
}
.fav_menu {
top : -10px ;
left : 95px ;
}
@keyframes move-forward {
from {
left : -200px ;
opacity : 0.1 ;
}
to {
left : 100px ;
opacity : 1 ;
}
}
@keyframes move-backward {
from {
left : 100px ;
opacity : 1 ;
}
to {
left : -200px ;
opacity : 0.1 ;
}
}