Chapter 11. jQuery 라이브러리
01 jQuery 라이브러리 설정
CDN(Content Delivery Network)는 파일을 여러 서버에 분산시키고 사용자가 접속하는 지역과 가장 가까운 곳의 서버에서 파일을 전송하는 기술이다.
웹사이트에 접속해서 CDN Uncompressed 버전 파일을 복사한다.
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title></title>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
</head>
<body>
$(document).ready(function(){
});
</body>
</html>
jQuery $(document).ready(function(){ });
02 문서 객체 선택
jQuery 형태
$(선택자).메소드(매개변수, 매개변수);
// Expose JQuery to the global object
window.jQuery = window.$ = jQuery;
기본 예제 11-1 문서 객체 선택
document.querySelectorAll() 메소드와 달리 반복문을 사용하지 않고 객체 여러 개를 한 꺼번에 선택 가능하다.
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title></title>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<script>
$().ready(function(){
// $('h1').css("backgroundColor", "black").css("color", "red");
$('h1').css("backgroundColor", "black");
$('h1').css("color", "red");
});
</script>
</head>
<body>
<h1>header</h1>
<h1>header</h1>
<h1>header</h1>
</body>
</html>
03 문서 객체 조작
1- 속성 조작
문서 객체 속성을 조작할 때는 attr() 메소드를 사용한다.
//img 태그의 src 속성을 추출
var src = $('img').attr('src');
11-2 문서 객체 속성 추출
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title></title>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<script>
$(document).ready(function(){
var src = $('script').attr('src');
alert(src);
});
</script>
</head>
<body>
</body>
</html>
- 속성 지정
1) 속성 값을 입력해 지정
2) 객체를 입력해 속성을 지정
3) 함수를 이용해 속성을 지정
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title></title>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<script>
//방법1
$('img').attr('src', './lucky.jpg');
//방법2
$('img').attr({
src : "./lucky.jpg",
width : 300,
height : 200
});
//방법3
$('img').attr('src', function (index){
var size = (index + 1) * 100;
//반환
return './lucky.jpg' + size + 'x100';
});
</script>
</head>
<body>
</body>
</html>
기본 예제 11-3 문서 객체 속성 조작
1- 속성 값을 입력해 속성 지정하기
11-3-1
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title></title>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<script>
$(document).ready(function(){
$('img').attr('src', './lucky.jpg');
$('img').attr('width', '100');
$('img').attr('alt', 'jQuery 라이브러리를 사용한 속성 지정');
// $('img').attr('src', './lucky.jpg').attr('width', '100').attr('alt', 'jQuery 라이브러리를 사용한 속성 지정');
});
</script>
</head>
<body>
<img>
<img>
<img>
</body>
</html>
2- 객체를 입력해 속성 지정하기
11-3-2 {목록은 중괄호 안에 넣기}
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title></title>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<script>
$(document).ready(function(){
$('img').attr({
alt : '속성을 이용한',
src : './lucky.jpg',
width : '200'
});
});
</script>
</head>
<body>
<img>
<img>
<img>
</body>
</html>
3- 함수를 이용해 속성 지정하기
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title></title>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<script>
$(document).ready(function(){
$('img').attr({
alt : 'jquery의 속성',
src : function(index){
var size = (index + 1) * 100;
//반환
return 'http://placehold.it/' + size + 'x100';
}
});
});
</script>
</head>
<body>
<img>
<img>
<img>
</body>
</html>
2- 스타일 조작 .css()
기본 예제 11-4 문서 객체 스타일 조작
1- 속성 값을 입력해 스타일 속성 지정하기
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>jQuery Basic</title>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<script>
$().ready(function(){
$('.box').css('width', 100).css('backgroundColor', 'red').css('height', 100)
.css('float','left').css('margin', 5);
});
</script>
</head>
<body>
<div class = "box"></div>
<div class = "box"></div>
<div class = "box"></div>
</body>
</html>
2- 객체를 입력해 스타일 속성 지정하기
css() 메소드의 매개변수에 객체를 넣은 후 코드 형태로도 스타일을 조작할 수 있습니다.
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>jQuery Basic</title>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<script>
$().ready(function(){
$('.box').css({
float : 'left',
margin : 5,
backgroundColor : 'blue',
width : 200,
height : 200
});
});
</script>
</head>
<body>
<div class = "box"></div>
<div class = "box"></div>
<div class = "box"></div>
</body>
</html>
3. 함수를 이용해 스타일 속성 지정
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>jQuery Basic</title>
<script>
$(document).ready(function(){
var output = '';
for (var i = 0; i < 256; i++) {
output += '<div></div>';
}
document.body.innerHTML = output;
$('div').css({
height : 2,
backgroundColor : function(i){
return 'rgb(' + i + ', ' + i + ', ' + i + ')';
}
});
});
</script>
</head>
<body>
<div class = 'box'></div>
<div class = 'box'></div>
<div class = 'box'></div>
</body>
</html>
html() 문서 객체 내부의 HTML 태그 조작
text() 문서 객체 내부의 글자 조작
기본 예제 11-5 문서 객체 글자 조작
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>jQuery Basic</title>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<script>
$(document).ready(function(){
$('h1:nth-child(1)').text('<a href = #> text() </a>');
$('h1:nth-child(2)').html('<a href = #> html() </a>');
});
</script>
</head>
<body>
<h1>Header - 0 </h1>
<h1>Header - 0 </h1>
</body>
</html>
2 html() 메소드로 내부 글자 조작하기
text()는 모든 텍스트를 추출하지만,
html() 메소드는 지금까지 살펴본 메소드처럼 첫 번째 위치한 문서 객체의 글자를 추출한다.
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>jQuery Basic</title>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
var text = $('h1').text();
var html = $('h1').html();
alert("Text : " + text);
alert("HTML : " + html);
});
</script>
</head>
<body>
<h1>Header - 0 </h1>
<h1>Header - 1 </h1>
</body>
</html>
4 클래스 조작
문서 객체의 class 속성 값을 띄어쓰기로 구분해 여러 개 입력할 수 있다.
<p class = "bold big italic">Lorem iipsum dolor amet</p>
* 클래스 조작 메소드
addClass() 클래스 추가
removeClass() 클래스 제거
toggleClass() 클래스 전환
기본 예제 11-6
정확히 hover가 어떤 메소드인지? 그리고 왜 .hover가 아닌 .hover#box가 쓰여야 하는지?
384p
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>jQuery Basic</title>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<style>
#box {
width : 150px;
height : 150px;
background-color : red;
}
#box.hover {
background-color : blue;
border-radius: 50%;
}
</style>
<script>
$(document).ready(function(){
$("#box").hover(
function(){
$("#box").addClass('hover');
}, function(){
$("box").removeClass('hover');
}
);
});
</script>
</head>
<body>
<div id = "box"></div>
</body>
</html>
04 이벤트
ready()는 간단한 이벤트 연결 메소드
ready()메소드를 사용하면 ready 이벤트(문서 객체 준비 완료 이벤트)가 연결된다.
ready 이벤트 이외에도 jQuery 라이브러리와 같이 간단한 이벤트 연결 메소드를 제공한다.
11-4 간단한 이벤트 연결 메소드
$(selector).method(function(event){});
기본 예제 11-7 click 이벤트 연결
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>jQuery Basic</title>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<style>
</style>
<script>
$(document).ready(function(){
$('#box').click(function(){
alert("클릭");
});
});
</script>
</head>
<body>
<h1 id = "box">Click</h1>
</body>
</html>
기본 예제 11-9 복합 이벤트 연결 메소드?
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<script>
$(document).ready(function () {
$('h1').hover(function () {
$(this).css({
background : 'red',
color : 'white'
});
}, function () {
$(this).css({
background : '',
color : ''
});
});
});
</script>
</head>
<body>
<h1>Click!</h1>
</body>
</html>
기본 예제 11-9
버전1 기존 style 속성 이용
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>jQuery Basic</title>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<style>
#box {
width : 100px;
height: 100px;
background-color: orchid;
}
</style>
<script>
$().ready(function(){
// $('#box').css({
// backgroundColor : 'orange',
// width : 100,
// height : 100,
// });
$('#box').click(function(){
$('#box').css({
backgroundColor : 'red'
});
});
$('#box').hover(function(){
$('#box').css({
backgroundColor : 'blue'
});
});
});
</script>
</head>
<body>
<div id = "box"></div>
</body>
</html>
버전2 on 기능
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>jQuery Basic</title>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<style>
</style>
<script>
$().ready(function(){
$('#box').css({
backgroundColor : 'orange',
width : 100,
height : 100
}).on('click', function() {
$(this).css('backgroundColor', 'red');
}).on('mouseenter', function(){
$(this).css('backgroundColor', 'blue');
}).on('mouseleave', function(){
$(this).css('backgroundColor', 'orange');
});
});
</script>
</head>
<body>
<div id = "box"></div>
</body>
</html>
기본 예제 11-10 기본 이벤트 제거
event.preventDefault();
<!DOCTYPE html>
<html>
<head>
<title>jQuery Basic</title>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script>
$().ready(function(){
$('a').click(function(event){
alert('click');
event.preventDefault();
});
});
</script>
</head>
<body>
<a href = "naver.com">한빛 미디어</a>
</body>
</html>
기본 예제 11-10-1 기본 이벤트 제거를 활용한 유효성 검사
replace(/가-힣/g, '').length == 0)
<!DOCTYPE html>
<html>
<head>
<title>jQuery Basic</title>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script>
$().ready(function(){
$('form').submit(function(event){
var value = $('input').val();
if (value.replace(/[가-힣]/g, '').length == 0) {
// 유효성 검사 통과
alert('과정을 진행합니다.');
} else {
// 유효성 검사 실패
alert('한글 이름을 입력해주세요.');
event.preventDefault();
}
});
});
</script>
</head>
<body>
<form>
<label>이름</label>
<input type = "text">
<input type = "submit">
</form>
</body>
</html>
기본 예제 11-11 태그가 사라졌다가 나타나는 효과
<!DOCTYPE html>
<html>
<head>
<title>jQuery Basic</title>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script>
$().ready(function(){
$('button').click(function(){
$('.toggle').fadeToggle();
});
});
</script>
</head>
<body>
<button>Toggle Show</button>
<div class = "toggle">
<h1>Lorem ipsum dolor sit amet</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>
</body>
</html>
기본 예제 11-12 애니메이션 효과
animate({속성 : 속성값}, 1000); opacity : 점점 투명하게 만들기
<!DOCTYPE html>
<html>
<head>
<title>jQuery Basic</title>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script>
$().ready(function(){
$('#box').css({
width : 100,
height : 100,
backgroundColor : 'red'
}).animate({
width : 300,
height : 300,
opacity : 0.5,
}, 1000);
});
</script>
</head>
<body>
<div id = "box"></div>
</body>
</html>
기본 예제 11-13 애니메이션 효과 정지
<!DOCTYPE html>
<html>
<head>
<title>Animation Basic</title>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script>
$(document).ready(function () {
// 변수를 선언합니다.
var clearQueue = false;
var goToEnd = false;
// 이벤트를 연결합니다.
$('#clearQueue').change(function () {
clearQueue = $(this).prop('checked')
});
$('#goToEnd').change(function () {
goToEnd = $(this).prop('checked');
});
$('#stopButton').click(function () {
$('#box').stop(clearQueue, goToEnd);
});
// 스타일을 변경합니다.
$('#box').css({
width: 100,
height: 100,
background: 'red'
})
// 타이머를 연결합니다.
setInterval(function () {
$('#box').animate({
width: 200
}, 1000).delay(1000).animate({
width: 100,
height: 100
}, 1000);
}, 3000);
});
</script>
</head>
<body>
<!-- 입력 양식 -->
<label>clearQueue</label>
<input id="clearQueue" type="checkbox">
<br>
<label>goToEnd</label>
<input id="goToEnd" type="checkbox">
<br>
<button id="stopButton">Stop</button>
<!-- 애니메이션 -->
<div id="box"></div>
</body>
</html>