이벤트 란?

마우스를 움직이거나 키를 입력하고, 창 크기를 조절하는 등 이런 행동들을 보고 이벤트가 발생했다라고 인식합니니다.


<--이벤트 종류-->

<--마우스 이벤트--> 

 이벤트

설명 

 click

 마우스 버튼을 클릭 하였을 때 발생

 dblclick

 마우스 버튼을 두 번클릭 하였을 때 발생 

 mousedown

 마우스를 누른 뒤 때지 않고 아래로 드레그 할 때

 mouseup

 마우스를 누른 뒤 떄지 않고 위로 드레고 할 때

 mouseover

 마우스를  HTML요소 위에 올리면 발생

 mouseout

 마우스가 HTML요소가 벗어 날 때 마우스 아웃 이벤트가 발생

 mousemove 

 마우스가 움직일 때 마다 발생


<--Document/WIndow 이벤트-->

 이벤트 

 설명 

 load

 웹 브라우저가 웹 페이지에 사용할 모든 파일의 다운로드를 완료 했을 때 발생

 resize

 최대화 버튼을 클릭하거나 브라우저 창의 크기를 조절하면 발생

 srcoll

 웹 페이지를 스크롤 할 때 발생(스크롤 바가 없으면 발생하지 않음)

 unload 

다른 페이지로 이동하거나 브라우저 탭을 닫거나 브라우저 창을 닫을 때 발생 


<--폼 이벤트-->

 이벤트

 설명 

 submit

 방문객이 폼을 전송할 떄 전송 이벤트 발생. 

 reset

 작성 헀던 폼을 완전히 초기화 가능

 change

 상태가 변경 되었을 때 발생(체크박스를 예로 들 수 있다.) 

 focus 

 탭을 누르거나 텍스트 필드를 클릭하면 이벤트 발생 

 blur

 탭을 누르거나 필드 바깥을 클릭해서 현재 포커스를 가진 필드에서 빠져나갈 때 


<--키보드 이벤트-->

 이벤트

 설명 

 keypress

 키를 누르는 순간 이벤트 발생(꾹 누르면 계속 발생)

 keydown

 키눌림 이벤트가 발생하기 직전에 발생. 

 keyup

 키를 눌렀다 떼는 순간에 발생  


<--이벤트 사용 방법-->

1. 이벤트를 할당 할 때.

$('menu').click();

△선택자 .click()형태로 추가해 줍니다.(click이 아닌 다른 이벤트 도)


2. 이벤트에 함수 전달 할 때.

$('menu').click(starthide());

△이벤트를 할당하고 이벤트의 ()안에 실행할 함수를 넣는는다.


3.익명함수로 사용할 때

$('menu').click(function(){

//code

});

▲ 선택자로 선택을한 뒤 이벤트를 할당해 주고, 이벤트의 괄호 안에 function을 넣는다.




'Programming > Java Script + jQuery' 카테고리의 다른 글

jQuery CSS 속성 읽고 바꾸기 & 익명함수  (1) 2015.12.14
jQuery 콘텐츠 추가!  (0) 2015.12.14
jQuery 선택자 & 필터  (0) 2015.12.11
jQuery 시작!  (0) 2015.12.09
블로그 이미지

KimMinSung

,

CSS속성을 읽거나 바꾸는 함수드들을 알아봅시다.

<--CSS 읽기/바꾸기-->



<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="js/jquery-1.11.2.js"></script>
	<title>Meta tag</title>

	<script type="text/javascript">
	  $('#content').ready(function(){
	    var B_ground = $(".test").css("background-color");
	    $(".test").css("background-color", '#FE0037');
	    alert(B_ground);
	  });
	</script>

	<style type="text/css">
		.test{
			background-color: blue;
		}
	</style>
</head>
<body>
	<div class = "test">
		Blue Text!
	</div>
</body>
</html>

▲위 코드는 간단히 CSS의 값을 받아와 출력하는 것과 CSS 변경 하는 것을 보여준다.

△위 스크립트 코드 2번째(CSS변경 코드)를 이용하면 CSS를 추가도 가능하다.



var baseFont = $('body').css('font-size');
baseFont = parseInt(baseFont,10);
$('body').css('font-size',baseFont);

△위의 또다른 예제는 font크기를 다른 폰트에도 똑같이 적용하는 것을 보여준다.

▲왜 복잡 하냐면 font-size를 변수에 넣을떄 XX px 의 꼴로들어 가게되는데 px부분을 제거하기  위해서 parseInt를 사용한다.


<--여러개의 CSS속성을 바꾸기-->

위의 예제 처럼 하나하나 바꿔줘야 할 때도 있지만 한번에 여려개를 바꿔야하는 경우도 있습니다. 한번 알아보자!


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="js/jquery-1.11.2.js"></script>
	<title>Meta tag</title>

	<script type="text/javascript">
	  $('body').ready(function(){
	    $('.test .syntax').css({'background-color' : 'red',
				    'font-size' : '20px',
				    'border' : '10px'});
	  });
	</script>
</head>
<body>
	<div class = "test">
		<p class = "syntax">Test syntax!!</p>
	</div>
</body>
</html>

▲2개 이상의 CSS속성을 줄때는 위 처럼 사용한다.

△css({'CSS' : '값' , 'CSS' : '값' , ....});


<--HTML 속성 읽고 설정하고 제거하기-->

HTML 속성 읽고 설정하는데에는 두개의 함수가 있습니다.

바로 attr(), removeAttr() 함수이다.


<--attr() & removeAttr()-->


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="js/jquery-1.11.2.js"></script>
	<title>Meta tag</title>

	<script type="text/javascript">
	  $('body').ready(function(){
	    var path = $('.test img').attr('src');
	    $('.test').append('<p>'+path+'</p>');
	    $('.test img').attr('src','http://postfiles6.naver.net/20150115_261/0314tnrud_1421325513038b1nCg_JPEG/%C4%AD%C4%DA%B7%B9_2%C8%AD_%289%29.jpg?type=w1');
	  });

	  $(function(){
	  $('.test #remove').click(function(){
	    $(".test img").removeAttr("src");
	  });
	});
	</script>
</head>
<body>
	<div class = "test">
		<img src="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcSBjR5_BavmJOTFrdKMFgi4xPZmbbY1gavKJO9UjNehmypOEI0I" width = "300" height="300">
		<input type = "button" value = "remov img" id = "remove">
	</div>
</body>
</html>

△처음 ready 함수는 append()로 원래 주소를 보여주고 attr()로 바꾼 이미지를 보여준다.

▲click()함수는 button을 클릭하면removeAttr()을 사용해 이미지가 사라지는 것을 보여준다.


<-- fadeOut() -->


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="js/jquery-1.11.2.js"></script>
	<title>Meta tag</title>

	<script type="text/javascript">
	  $(function(){
	  $('.test #remove').click(function(){
	    $(".test img").fadeOut();
	  });
	});
	</script>
</head>
<body>
	<div class = "test">
		<img src="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcSBjR5_BavmJOTFrdKMFgi4xPZmbbY1gavKJO9UjNehmypOEI0I" width = "300" height="300">
		<input type = "button" value = "fade Out" id = "remove">
	</div>
</body>
</html>

△fadeOut()적용 예제이다. 서서히 사라지는 것을 볼 수있다.


<-- Each와 익명 함수 -->

$('   ').each(function(){
	  		//code
});

each는 함수의 시작을 알려주고, function()은 익명함수이다.


책에 나오는 사용법으로는 주로 반복을 하는 코드일 때 사용한다고 나온다.


$('img').each(function(){
       alert("img!");
});

△이미지가 한 10개 정도 있는 페이지에 저렇게 쓰면 10번 출력될 것 이다...


사용예
	<script type="text/javascript">
	$(document).ready(function(){
	  	$('a[href^="http://"]').each(function(){
	  			var extLink = $(this).attr('href');
	  			alert(extLink);
	  	});
	});
	</script>
</head>
<body>
	<a href="http://www.naver.com/"></a>
	<a href="http://www.daum.net/"></a>
	<a href="https://www.google.co.kr/?gws_rd=ssl"></a>
</body>

▲위의 this는 $('a[href^="http://"]')를 가리키고 있다.

△순서 대로 찾으면서 하나씩 alert로 출력 해줄 것 이다.

'Programming > Java Script + jQuery' 카테고리의 다른 글

jQuery 이벤트 사용하기!  (0) 2015.12.16
jQuery 콘텐츠 추가!  (0) 2015.12.14
jQuery 선택자 & 필터  (0) 2015.12.11
jQuery 시작!  (0) 2015.12.09
블로그 이미지

KimMinSung

,

<--페이지에 콘텐츠 추가-->

-페이지에 콘텐츠를 다루는 함수를 알아보자!

우리가 사용할 예제 코드를 봅시다.


<body>
<div id = "header">
	<div class = "Message">
		<h2>Error Message!</h2>
	</div>
</div>
</body>

▲이번 콘텐츠 추가에 우려먹을 코드


<-- .html() -->


<script type="text/javascript">
		$(document).ready(function(){
			alert($('.Message').html());
			$('.Message').html('<p>Wrong!!!</p>');
		});// 끝
</script>

#alert부분 처럼 사용하면 특정 HTML 요소 내부의 HTML을 복사해 다른 HTML요소에 전달이 가능합니다

#두번째 처럼 문자열을 인수로 줄 경우에는 문자열이 치환 됩니다.


▲처음은 ErrorMessage라는 경고창이 뜨지만 확인을 누르면 문자열이 Wrong!!!으로 바뀐다.


<-- .text() -->


<script type="text/javascript">
		$(document).ready(function(){
			$(".Message h2").text("Hello World");
		});// 끝
</script>

#문자열을 " Hello Message "로 치환해 줍니다.


▲Error Message 가 Hello World로 치환된 것을 볼 수 있습니다.


<-- .append() & prepend() -->


<script type="text/javascript">
		$(document).ready(function(){
			$(".Message").append("<p>append Error</p>");                        $(".Message").prepend("<p>prepend Error</p>");		});// 끝
</script>

#HTML요소에 HTML을 추가할 떄 사용합니다.


▲위를 보면 prepend는 html 상단에 추가되고, append는 하단에 추가되는 것을 볼 수 있다!


<-- .before() & .after() -->

-선택한 HTML요소 바깥에 HTML을 추가하고 싶을 때 사용하는 명령어.

-befoer은 HTML요소 앞에 after은 뒤에 추가한다.

Ex)

Id를 받는 폼이 있을 때 사용자가 Id를 입력 안했다면, "사용자 이름 입력"이라는 문구를 띄울 떄 사용한다.


<-- .remove() & .replace() -->


<script type="text/javascript">
		$(document).ready(function(){
				$('div.Message').remove();
				$('#header').append('<div class = "New"><p>New Div</p></div>');
		});// 끝
</script>

#remove로 삭제해보았습니다..

#replace는 잘 몰라서 .... 나중에 사용해 봐야것지..


▲삭제 된 뒤 새로운 DIV를 추가해 보았다


<-- .addclass() & .removeclass() -->


	<script type="text/javascript">
		$(document).ready(function(){
			$('#header .Message h2').addClass('add_h2');
		});// 끝
	</script>

#addClas()로 h2에 class를 추가시켜 보았다.



	<script type="text/javascript">
		$(document).ready(function(){
			$('#header .Message h2').addClass('add_h2');
			$('#header .Message .add_h2').removeClass('add_h2');
		});// 끝
	</script>

#removeClass를 사용하여 add_h2를 지워보았다.


<-- .toggleClass() -->


	<title>Meta tag</title>

	<script type="text/javascript">
	$(function(){
	  $('#content').click(function(){
	    $("body").toggleClass("change_body");
	  });
	});
	</script>

	<style type="text/css">
		body{
			width: 100px;
			height: 100px;
			background-color: blue;
		}
		.change_body{
			width: 100px;
			height: 100px;
			background-color: red;
		}
	</style>
</head>
<body>
	<input type = "button" value="Button" id = "content">
</body>

▲toogle클래스를 사용하여 class를 생성했다가 버튼을 누르면 삭제되는 예제.

△toogle은 class가 없으면 class를 생성 있으면 삭제하는 역할을 한다.



'Programming > Java Script + jQuery' 카테고리의 다른 글

jQuery 이벤트 사용하기!  (0) 2015.12.16
jQuery CSS 속성 읽고 바꾸기 & 익명함수  (1) 2015.12.14
jQuery 선택자 & 필터  (0) 2015.12.11
jQuery 시작!  (0) 2015.12.09
블로그 이미지

KimMinSung

,