css에서 다룰 수 있는 애니메이션 효과들을 jq에서 다뤄보자.


animate() : 지정한 스타일로 서서히 변함


show() : 보이기


hide() : 숨기기


toggle() : 보이거나 숨기기


animate

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script
  src="http://code.jquery.com/color/jquery.color-2.1.2.js"
  integrity="sha256-1Cn7TdfHiMcEbTuku97ZRSGt2b3SvZftEIn68UMgHC8="
  crossorigin="anonymous"></script>
<style type="text/css">
	.test1{
		width: 200px;
		height: 200px;
		background: orangered;
	}
</style>
</head>
<body>
	<h1>Effect메소드</h1>
	<p>페이지에 애니메이션 효과를 만들기 위한 메소드 집합</p>
	<h3>animate() 메소드</h3>
	<div id="test1" class="test1"></div>
	<button id="btn">animation 적용</button>
	
	<script type="text/javascript">
		$(function() {
			$("#btn").click(function() {
				// 적용될 애니메이션, 실행 시간, 끝나고 실행될 함수
				// 하지만 기본적으로 backgroundColor는 컨트롤 못하게 해놓았다.
				$("#test1").animate({width:"500px", backgroundColor:"blue"}, 3000, function() {
					alert("애니메이션 적용 완료")
				});
				// 배경 색을 바꾸려면 jquery 홈페이지에서 플러그인을 받아서 적용해야 한다.
			});
		});
	</script>

</body>
</html>


배경색의 경우는 jquery 파일을 하나 더 추가해야 한다.


jquery 홈페이지에서 plug in 메뉴를 누르고





리스트 중 animation의 페이지 두번째 (바뀔 수 있다) jquery color를 선택해서


Download 버튼을 누르면 다음과 같은 페이지가 뜬다.




버전에 맞는 링크를 누르면 script가 나오는데 복사해서 코드 상단에 붙여넣으면 된다.






<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style type="text/css">
	div{
		width: 50px;
		height: 50px;
		background: orangered;
		position: relative;
		
	}
</style>
<script type="text/javascript">
	// Position은 대개 relative나 absolute 두 개를 자주 사용하는데
	// relative는 자기 부모 객체를 기준으로 삼는 것이고
	// absolute는 현재 페이지 자체를 기준으로 위치를 설정하게 된다.
</script>
</head>
<body>
	<h1>상대적 애니메이션</h1>
	<div></div>
	<div></div>
	<div></div>
	<div></div>
	<div></div>
	<div></div>
	<div></div>
	<script type="text/javascript">
		$(function() {
			$("div").click(function() {
				var width = $(this).css("width");
				var height = $(this).css("height");
				
				$(this).animate({
					width:parseInt(width) + 50,
					height:parseInt(height) + 50
				}, "slow");
			});
			
			$("div").each(function(index) {
				$(this).delay(index * 50).animate({left:500}, "slow");
			});
		});
		
	</script>
</body>
</html>



show, hide, toggle

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
	<h1>시각적 효과</h1>
	<h3>show()와 hide()</h3>
	<p>문서 객체를 크게 하며 보여주거나 작게하며 사라지게 한다.</p>
	<button id="show">보여주기</button>
	<button id="hide">숨기기</button>
	<img id="river" src="../image/river1.PNG">
	<hr>
	
	<script type="text/javascript">
		$(function() {
			$("#show").click(function() {
				$("#river").show();
			});
			$("#hide").click(function() {
				$("#river").hide();
			});
		});
	</script>
	
	<br>
	
	<button id="toggle">토글하기</button>
	<br>
	<img id="forest" src="../image/forest1.PNG">
	
	<script type="text/javascript">
		$(function() {
			/* var ctn = 0;
			$("#toggle").click(function() {
				ctn++;
				if (ctn % 2 != 0) {
					$("#forest").hide();
				}else {
					$("#forest").show();
				}
			}); */
			// 따로 메소드가 또 있다.
			
			$("#toggle").click(function(){
				$("#forest").toggle(3000, function(){
					alert("토글완료");
				});
			});
		});
	</script>

	
	
</body>
</html>


JQuery문을 이용해서 이벤트를 활성화 하는 법을 알아보자.


bind() : 현재 문서에 존재하는 객체에 event 속성을 부여


unbind() : bind로 생성된 이벤트 제거


on() : 1.7 버전 이후로 쓰이고 bind와 기능은 같다. bind보단 on을 사용하길 권장한다.


off() : on으로 생성된 이벤트 제거





bind('이벤트명', function)으로 사용하고


on은 on('이벤트명':function, '이벤트명':function, '이벤트명':function, '이벤트명':function, .....) 과 같이 사용한다.



<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
	#test2, #test3 {
		width:300px;
		height:300px;
		background:orangered;
	}
</style>
</head>
<body>
	<h1>이벤트</h1>
	<h3>이벤트 관련 속성</h3>
	<button onclick="test1(event)">실행 확인</button>
	
	<script type="text/javascript">
		function test1(event) {
			console.log(event);
		}
	</script>
	
	<hr>
	
	<h3>이벤트 연결 종류</h3>
	<h4>bind() : 현재 존재하는 문서 객체만 이벤트 연결<br>
	unbind() : bind()로 연결된 이벤트 제거</h4>
	<h1 id="test1">마우스를 올려보세요</h1>
	<script>
		$(function(){
			$("#test1").bind('mouseenter', function(){
				$(this).css({"background":"black", "color":"white"});
			}).bind('mouseleave', function(){
				$(this).css({"background":"white", "color":"black"});
			});
			
			$("#test1").bind('click', function(){
				$(this).unbind('mouseenter').unbind('mouseleave').css({"background":"white", "color":"black"});
			});
		});
	</script>
	
	<h4>on() : bind()대신에 on으로 대체됨<br>
	off() : on()으로 연결된 이벤트 제거</h4>
	<div id="test2">기본상태</div>
	<script>
		$(function(){
			$("#test2").on({'mouseenter':function(){
				$(this).css("background", "yellowgreen").text("마우스 올라감");
			}, 'mouseleave':function(){
				$(this).css("background", "yellow").text("마우스 내려감");
			}, 'click':function(){
				$(this).off('mouseenter').off('mouseleave').css("background", "orangered").text("기본값");
			}});
		});
	</script>
	
	<br>
	
	<div id="test3">기본상태</div>
	<script type="text/javascript">
		$(function() {
			$("#test3").on("click", {name : "김가루"}, function(event) {
				alert(event.data.name + "님 환영합니다!");
			});		
		});
	</script>
	
	<br>
	
	<div id="wrap">
		<h2>Header</h2>
	</div>
	<script>
		$(function(){
			$(document).on('click', 'h2', function(){
				var length = $("h2").length;
				var targetHTML = $(this).html();
				
				console.log(length);
				console.log(targetHTML);
				
				$("#wrap").append("<h2>" + targetHTML + " - " + length + "</h2>");
			});
		});
	</script>
	
	<hr>
	
	<h3>one() 메소드</h3>
	<p>이벤트를 한 번만 연결할 때 사용한다.</p>
	<h1 id="test4">클릭하세요</h1>
	<script type="text/javascript">
		$(function() {
			$("#test4").one("click", function() {
				alert("이벤트 발생!!");
			});
		});
	</script>
</body>
</html>









jq에서 이벤트를 지정하는 다른 방법은


$(불러올 객체).이벤트명(function)과 같이 쓴다.


이와 같이 다양한 이벤트 지정 방법이 존재하므로 마음에 드는 방법을 사용하면 된다.


mouseover, mouseenter, hover, keydown, keypress, keyup, click, change, focus 등 다양한 이벤트 키워드들이 있고


이 중 hover이나 focus 같이 사용법이 특이한 경우도 있으므로 예에서 잘 확인해보자



<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style type="text/css">
	.inner{
		width: 100%;
		height: 100%;
		background: red;
	}
	.outer{
		width: 200px;
		height: 200px;
		background: orange;
		padding: 50px;
	}
	.reverse{
		background: black;
		color: white;
	}
</style>

</head>
<body>
	<h1>이벤트 연결 메소드</h1>
	<h3>mouseover와  mouseenter</h3>
	<div class="outer">
		<div class="inner"></div>
	</div>
	
	<script type="text/javascript">
		// mouseover는 요소에 마우스 포인터가 진입하면 발생
		// (직접 이벤트를 걸지 않은 자식요소에 포인터가 와도 발생함)
		// mouseenter는 오로지 자신에게 마우스 포인터가 와야만 발생함
		$(function() {
			$(".outer").mouseover(function() {
				console.log("OVER!");
			});
			$(".outer").mouseenter(function() {
				console.log("ENTER")
			});
		});
	</script>
	
	<h3>hover() 메소드</h3>
	<p>mouseenter와 mouseleave를 동시에 사용하는 효과이다.</p>
	<h1 id="test1">hover테스트</h1>
	<script type="text/javascript">
		$(function() {
			$("#test1").hover(
					function() { // 첫번째는 mouseenter
						$(this).addClass("reverse");
					},
					function() { // 두번째는 mouseleave
						$(this).removeClass("reverse");
					}
			);
		});
	</script>
	
	<h3>키보드이벤트</h3>
	<p>keydown : 키보드가 눌려질 때<br>
	keypress : 글자가 입력될 때<br>
	keyup : 키보드가 떼어질 때</p>
	<h4>동적으로 글자 수 세기</h4>
	<div>
		<h1 id="counter">150</h1>
		<textarea rows="5" cols="70"></textarea>
	</div>
	<script type="text/javascript">
		$(function() {
			$("textarea").keydown(function() {
				var inputLength = $(this).val().length;
				var remain = 150 - inputLength;
				
				$("#counter").html(remain);
				
				if (remain >= 0) {
					$("#counter").css("color", "black");
				}else {
					$("#counter").css("color", "red");
				}
			});
		});
	</script>
</body>
</html>


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
	.trg {
		width:100px;
		height:100px;
		background:orangered;
		text-align:center;
		vertical-align:middle;
		cursor:pointer;
	}
	.increment {
		background:black;
		width:100px;
		height:25px;
		color:white;
		text-align:center;
		margin-top:20px;
		cursor:pointer;
	}
</style>
</head>
<body>
	<h1>입력 양식 이벤트</h1>
	<div id="wrap">
		<h1 align="center">회원 가입</h1>
		<form>
			<table align="center">
				<tr>
					<td><label>이름</label></td>
					<td><input type="text" name="name" id="name"></td>
					<td><label id="nameresult"></label></td>
				</tr>
				<tr>
					<td><label>아이디</label></td>
					<td><input type="text" name="userid" id="userid"></td>
					<td><input type="button" value="중복확인"></td>
				</tr>
				<tr>
					<td><label>비밀번호</label></td>
					<td><input type="password" name="pwd1" id="pwd1"></td>
					<td></td>
				</tr>
				<tr>
					<td><label>비밀번호 확인</label></td>
					<td><input type="password" name="pwd2" id="pwd2"></td>
					<td><label id="pwdresult"></label></td>
				</tr>
				<tr>
					<td><label>이메일</label></td>
					<td><input type="email" name="email" id="email"></td>
					<td></td>
				</tr>
				<tr>
					<td></td>
					<td><input type="submit"> &nbsp; <input type="reset"></td>
					<td></td>
				</tr>
			</table>
		</form>
	</div>
	
	<script type="text/javascript">
		$("#name").change(function(){
			var regExp = /[가-힣]/;
			
			if(!regExp.test($(this).val())){
				$("#nameresult").html("한글로 입력하세요").css("color", "red");
				$(this).focus().css("background","red");
			}else{
				$("#nameresult").html("정상입력").css("color","green");
			}
		
		});
			
		$("#pwd2").change(function(){
			if($("#pwd1").val() != $(this).val()){
				$("#pwdresult").html("비밀번호가 일치하지 않습니다").css("color","red");
				$("#pwd2").val('');
				$(this).select();
			}else{
				$("#pwdresult").html("비밀번호 일치").css("color","green");
			}
		});
		
		$("#name").focus(function(){
			console.log('focus이벤트 가동');
		}).focusin(function(){
			console.log('focusin이벤트 가동');
		}).focusout(function(){
			console.log('focusout이벤트 가동');
		}).blur(function(){
			console.log('blur이벤트 가동');
		}).change(function(){
			console.log('change이벤트 가동');
		}).select(function(){
			console.log('select이벤트 가동');
		})
		
		$("form").submit(function(event){
			alert("submit이벤트 동작");
			event.preventDefault();
		});

	</script>
	
	
	<div id="result"></div>
	<script>
		$(function(){
			$("input[type=submit]").click(function(){
				$("#result").html("이름 : " + $("#name").val());
			});
			
		});
	</script>
	
	<hr>
	
	<h3>trigger()메소드</h3>
	<div class="trg" id="trg">
		click Num : <span>0</span>;
	</div>
	<div class="increment" id="increment">click me!</div>

	<script type="text/javascript">
		var ctn = 0;
		
		$(function() {
			$("#trg").on("click", function() {
				ctn++;
				$("span").text(ctn);
			});
		});
		
		$("#increment").click(function() {
			$("#trg").trigger("click");
		});
	</script>
	
	
</body>
</html>


jq에서 자주 사용하는 메소드를 알아보자.




each() 반복문은 for in과 비슷하다. 반복문을 태그에 쓰는 것으로 여러 태그를 불러 왔을 때 


간편하게 일괄 처리 할 수 있다. 그리고 그의 순서와 값은 key 와 value인 index와 item을 사용한다.


index는 가져온 태그의 순서, item은 해당 값을 의미한다.


 


addClass(" ") : addClass는 말 그대로 속성값 class를 추가해준다.


removeClass(" ") : addClass는 말 그대로 속성값 class를 제거해준다.


toggleClass(" ") : toggleClass는 클릭 했을 때 클래스가 적용 or 해제되는 속성을 추가


is() : 해당 객체(요소)가 괄호에 입력한 객체인지 판별해주는 메소드 (true & false)


$.extend() : 객체에 속성을 추가하거나 객체와 객체를 합치는 메소드


$.noConflict() : js 라이브러리나 다른 버젼의 jquery의 $ 키워드 충돌을 방지하기 위해 사용하고


이 키워드를 사용하면 $ 달러 키워드를 다른것으로 바꿔 사용 할 수 있다.



어떻게 쓰이는지 확인해보자



<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
	.high_light_0 {background:yellow;}
	.high_light_1 {background:orange;}
	.high_light_2 {background:blue;}
	.high_light_3 {background:green;}
	.high_light_4 {background:red;}
</style>
</head>
<body>
	<h1>메소드</h1>
	
	<h3>each() 메소드</h3>
	<p>배열을 관리하는 for in문과 비슷한 기능을 하는 메소드이다.</p>
	<p>$.each(object, function(index, item){})의 형식으로 사용한다.<br>
	index : 배열의 인덱스 또는 객체의 키를 의미한다.<br>
	item : 해당 인덱스나 키가 가진 값을 의미한다.</p>
	
	<script type="text/javascript">
		/*
		$(function() {
			var arr = [
				{name:"A", link:"http://www.naver.com"},
				{name:"B", link:"http://www.google.com"},
				{name:"C", link:"http://www.w3c.com"},
				{name:"D", link:"http://www.daum.net"}
			];
			
			$.each(arr, function(index, item) {
				var output = "";
				output += "<a href=" + item.link + ">";
				output += "<h2>" + item.name + "</h2>";
				output += "</a>";
				
				document.body.innerHTML += output;
			});
			
			
		})
		*/
	</script>
	
	<hr>
	
	<div id="wrap">
		<h1>item-0</h1>
		<h1>item-1</h1>
		<h1>item-2</h1>
		<h1>item-3</h1>
		<h1 id="item4">item-4</h1>
	</div>
	<script>
		$(function() {
			$("#wrap").children().each(function(index, item) {
				// 문서 객체에 class 속성을 추가하는 메소드
				$(this).addClass("high_light_" + index);
				
				if(index == 2){
					$(this).removeClass("high_light_" + index);
				}
			});
			
			$("#item4").click(function() {
				$(this).toggleClass("high_light_4");
			});
			
		})
	</script>
	
	<hr>
	
	<h3>문서 객체의 특징 판별 : is()</h3>
	<p>매개변수로 선택자를 입력하고, 선택한 객체가 선택자와 일치하는지 판단하여 boolean 리턴</p>
	<h3 class="test">test1</h3>
	<h3>test2</h3>
	<h3 class="test">test3</h3>
	<h3 class="test">test4</h3>
	<h3>test5</h3>
	<h3 class="test">test6</h3>
	
	<script>
		$(function(){
			$("h3").each(function(){
				if($(this).is(".test")){
					$(this).css({"background":"orangered", "color":"white"})
				}
			});
			
		});
	</script>
	
	<hr>
	
	<h3>$.extend() 메소드</h3>
	<p>객체에  속성을 추가하거나 여러개의 객체를 하나로 합칠 때 사용한다.</p>
	<script type="text/javascript">
		$(function() {
			var obj1 = {
					name:"김김김",
					age:20
			}
			var obj2 = {
					name:"님님님",
					hobby:["낚시", "영화"]
			}
			
			$.extend(obj1, {job:"강사"});
			
			console.log(obj1);
			console.log(obj2);
			
			
			// 두 객체를 하나로 합칠 때 사용 할 수 있다.
			// 중복되는 객체의 속성은 나중의 것으로 덮어 쓴다.
			var objs1 = $.extend(obj1, obj2);
			
			console.log(objs1);
		})
	</script>
	
	<hr>
	
	<h3>$.noConflict()</h3>
	<p>다른 라이브러리나 다른 버전의 jquery와 '$'의 충돌 방지를 위해 사용한다.</p>
	
	<h1 id="test">noConflict() 테스트</h1>
	
	<script type="text/javascript">
		/*
		var jq = $.noConflict(); // 이 키워드를 통해 $ 키워드 대신 jq를 사용 할 수 있게 된다. 
		
		jq(function() {
			jq("#test").css("color", "red");
		})
		*/
		// 위의 주석문을 해제하면 페이지의 모든 $가 jq로 바뀌므로 $로 호출한 함수들은 사용할 수 없다.
	</script>
	
	<!-- 다른 버전의 jquery와 충돌나는 경우 예시 -->
	<!-- <script src="jquery-1.11.1.js">
		var jb = jQuery.noConflict();
	</script>
	<script src="jquery-2.1.1.js">
		var hs = jQuery.noConflict();
	</script> -->
	
	
</body>
</html>



attr() : 해당 객체의 속성을 바꾸거나 확인 할 수 있는 메소드


css() : 해당 객체의 스타일을 바꾸거나 확인 할 수 있는 메소드



<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style type="text/css">
	.first{color: red;}
	.second{color: pink;}
	.third{color: orange;}
</style>
</head>
<body>
	<h3>attr() 메소드</h3>
	<p>문서 객체의 특정 속성 값을 알아내거나 속성을 추가할 때 사용한다.</p>
	<img src="../image/flower1.PNG" width="400px" height="300px">
	
	<script>
		$(function(){
			// 속성 명에 해당하는 속성 값을 리턴
			var img = $("img").attr("src");
			console.log("사진경로 : " + img);
			
			// 속성명에 해당하는 속성 값을 변경
			$("img").attr("src", "../image/flower2.PNG");

			// 함수를 통해 인덱스와 value를 활용할 수 있음
			$("img").attr("src", function(index, value){
				console.log(index, value);
			});
			
			// 객체를 통해 여러 속성을 설정
			$("img").attr({"width":"100px", "height":"50px"});
			
			// 객체의 속성을 제거
			$("img").removeAttr("width").removeAttr("height");
			
		});
	</script>
	
	<hr>
	
	<h3>css() 메소드</h3>
	<p>문서 객체의 스타일을 검사하거나 변경할 때 사용한다.</p>
	<h1 class="first">test-0</h1>
	<h1 class="second">test-1</h1>
	<h1 class="third">test-2</h1>
	
	<script type="text/javascript">
		$(function() {
			// 속성 명에 해당하는 속성 값을 리턴
			console.log($(".first").css("color"));
			
			// 속성명에 해당하는 속성 값을 변경
			$(".first").css("color", "black");
			
			// 함수를 통해 인덱스와 value를 활용할  수 있음
			$(".first").css("color", function(index, value) {
				console.log(index, value);
			});
			
			//객체를 통해 여러 속성을 지정
			$(".first").css({"font-size":"3em", "background":"orange"});
		
		})
	</script>
</body>
</html>




+ Recent posts