handling (3)

We have the ability to create dynamic web pages by using events. Events are actions that can be detected by your Web Application.

Following are the examples events:

  • A mouse click
  • A web page loading
  • Taking mouse over an element
  • Submitting an HTML form
  • A keystroke on your keyboard
  • etc.

When these events are triggered you can then use a custom function to do pretty much whatever you want with the event. These custom functions call Event Handlers.


이벤트 핸들러 바인딩하기

Using the jQuery Event Model, we can establish event handlers on DOM elements with the bind() method as follows:

$('div').bind('click', function( event ){
   alert('Hi there!');
});

This code will cause the division element to respond to the click event; when a user clicks inside this division thereafter, the alert will be shown.

The full syntax of the bind() command is as follows:

selector.bind( eventType[, eventData], handler)

Following is the description of the parameters:

  • eventType: A string containing a JavaScript event type, such as click or submit. Refer to the next section for a complete list of event types.

  • eventData: This is optional parameter is a map of data that will be passed to the event handler.

  • handler: A function to execute each time the event is triggered.


이벤트 핸들러 삭제하기

Typically, once an event handler is established, it remains in effect for the remainder of the life of the page. There may be a need when you would like to remove event handler.

jQuery provides the unbind() command to remove an exiting event handler. The syntax of unbind() is as follows:

selector.unbind(eventType, handler)

or 

selector.unbind(eventType)

Following is the description of the parameters:

  • eventType: A string containing a JavaScript event type, such as click or submit. Refer to the next section for a complete list of event types.

  • handler: If provided, identifies the specific listener that has to be removed.


이벤트 타입

The following are cross platform and recommended event types which you can bind using JQuery:

Event TypeDescription
blurOccurs when the element loses focus
changeOccurs when the element changes
clickOccurs when a mouse click
dblclickOccurs when a mouse double-click
errorOccurs when there is an error in loading or unloading etc.
focusOccurs when the element gets focus
keydownOccurs when key is pressed
keypressOccurs when key is pressed and released
keyupOccurs when key is released
loadOccurs when document is loaded
mousedownOccurs when mouse button is pressed
mouseenterOccurs when mouse enters in an element region
mouseleaveOccurs when mouse leaves an element region
mousemoveOccurs when mouse pointer moves
mouseoutOccurs when mouse pointer moves out of an element
mouseoverOccurs when mouse pointer moves over an element
mouseupOccurs when mouse button is released
resizeOccurs when window is resized
scrollOccurs when window is scrolled
selectOccurs when a text is selected
submitOccurs when form is submitted
unloadOccurs when documents is unloaded


이벤트 객체

The callback function takes a single parameter; when the handler is called the JavaScript event object will be passed through it.

The event object is often unneccessary and the parameter is omitted, as sufficient context is usually available when the handler is bound to know exactly what needs to be done when the handler is triggered, however there are certail attributes which you would need to be accessed.

이벤트 속성

The following event properties/attributes are available and safe to access in a platform independent manner:

PropertyDescription
altKeySet to true if the Alt key was pressed when the event was triggered, false if not. The Alt key is labeled Option on most Mac keyboards.
ctrlKeySet to true if the Ctrl key was pressed when the event was triggered, false if not.
dataThe value, if any, passed as the second parameter to the bind() command when the handler was established.
keyCodeFor keyup and keydown events, this returns the key that was pressed.
metaKeySet to true if the Meta key was pressed when the event was triggered, false if not. The Meta key is the Ctrl key on PCs and the Command key on Macs.
pageXFor mouse events, specifies the horizontal coordinate of the event relative from the page origin.
pageYFor mouse events, specifies the vertical coordinate of the event relative from the page origin.
relatedTargetFor some mouse events, identifies the element that the cursor left or entered when the event was triggered.
screenXFor mouse events, specifies the horizontal coordinate of the event relative from the screen origin.
screenYFor mouse events, specifies the vertical coordinate of the event relative from the screen origin.
shiftKeySet to true if the Shift key was pressed when the event was triggered, false if not.
targetIdentifies the element for which the event was triggered.
timeStampThe timestamp (in milliseconds) when the event was created.
typeFor all events, specifies the type of event that was triggered (for example, click).
whichFor keyboard events, specifies the numeric code for the key that caused the event, and for mouse events, specifies which button was pressed (1 for left, 2 for middle, 3 for right)

 

 

이벤트 객체의 메소드

There is a list of methods which can be called on an Event Object:

MethodDescription
preventDefault()Prevents the browser from executing the default action.
isDefaultPrevented()Returns whether event.preventDefault() was ever called on this event object.
stopPropagation() Stops the bubbling of an event to parent elements, preventing any parent handlers from being notified of the event.
isPropagationStopped() Returns whether event.stopPropagation() was ever called on this event object.
stopImmediatePropagation() Stops the rest of the handlers from being executed.
isImmediatePropagationStopped()Returns whether event.stopImmediatePropagation() was ever called on this event object.


이벤트 조작 관련 메소드

Following table lists down important event-related methods:

MethodDescription
bind( type, [data], fn )Binds a handler to one or more events (like click) for each matched element. Can also bind custom events.
die( type, fn )This does the opposite of live, it removes a bound live event.
hover( over, out )Simulates hovering for example moving the mouse on, and off, an object.
live( type, fn )Binds a handler to an event (like click) for all current - and future - matched element. Can also bind custom events.
one( type, [data], fn )Binds a handler to one or more events to be executed once for each matched element.
ready( fn )Binds a function to be executed whenever the DOM is ready to be traversed and manipulated.
toggle( fn, fn2, fn3,... )Toggle among two or more function calls every other click.
trigger( event, [data] )Trigger an event on every matched element.
triggerHandler( event, [data] )Triggers all bound event handlers on an element .
unbind( [type], [fn] )This does the opposite of bind, it removes bound events from each of the matched elements.


이벤트 핸들러 메소드

jQuery also provides a set of event helper functions which can be used either to trigger an event to bind any event types mentioned above.

트리거 메소드

Following is an example which would triggers the blur event on all paragraphs:

$("p").blur();

바인딩 메소드

Following is an example which would bind a click event on all the <div>:

$("div").click( function () { 
   // do something here
});

 

 

Here is a complete list of all the support methods provided by jQuery:

MethodDescription
blur( )Triggers the blur event of each matched element.
blur( fn )Bind a function to the blur event of each matched element.
change( )Triggers the change event of each matched element.
change( fn )Binds a function to the change event of each matched element.
click( )Triggers the click event of each matched element.
click( fn )Binds a function to the click event of each matched element.
dblclick( )Triggers the dblclick event of each matched element.
dblclick( fn )Binds a function to the dblclick event of each matched element.
error( )Triggers the error event of each matched element.
error( fn )Binds a function to the error event of each matched element.
focus( )Triggers the focus event of each matched element.
focus( fn )Binds a function to the focus event of each matched element.
keydown( )Triggers the keydown event of each matched element.
keydown( fn )Bind a function to the keydown event of each matched element.
keypress( )Triggers the keypress event of each matched element.
keypress( fn )Binds a function to the keypress event of each matched element.
keyup( )Triggers the keyup event of each matched element.
keyup( fn )Bind a function to the keyup event of each matched element.
load( fn )Binds a function to the load event of each matched element.
mousedown( fn )Binds a function to the mousedown event of each matched element.
mouseenter( fn )Bind a function to the mouseenter event of each matched element.
mouseleave( fn )Bind a function to the mouseleave event of each matched element.
mousemove( fn )Bind a function to the mousemove event of each matched element.
mouseout( fn )Bind a function to the mouseout event of each matched element.
mouseover( fn )Bind a function to the mouseover event of each matched element.
mouseup( fn )Bind a function to the mouseup event of each matched element.
resize( fn )Bind a function to the resize event of each matched element.
scroll( fn )Bind a function to the scroll event of each matched element.
select( )Trigger the select event of each matched element.
select( fn )Bind a function to the select event of each matched element.
submit( )Trigger the submit event of each matched element.
submit( fn )Bind a function to the submit event of each matched element.
unload( fn )Binds a function to the unload event of each matched element.

 

 

 

 

 

 Reference : http://www.tutorialspoint.com/jquery/jquery-events.htm

 

 

 

 

프로그래밍에는 세가지 종류의 에러가 있습니다.

 (a) 문법에러 (b) 런타임 에러 (c) 논리적 에러

문법 에러

문법에러는 파싱에러라고도 합니다. 문법상 맞지 않아서 발생하는 에러죠. 문법에러는 컴파일시에 에러가 있다고 알려주기때문에 찾기쉬운 에러입니다.

아래 예제는 닫는 괄호를 빼먹은 문법에러입니다.

<script type="text/javascript">
<!--
window.print(;
//-->
</script>

 

런타임 에러

런타임에러는 예외라고도 하며 실행시에 에러가 발생합니다. 아래 예제는 문법은 어긋나지 않지만 실행시에 오류가 발생합니다. 왜냐하면 존재하지 않는 메소드를 호출하려고 하기 때문이죠.

<script type="text/javascript">
<!--
window.printme();
//-->
</script>

 

논리적 에러

논리적으로 에러가 발생한 것은 찾기가 힘든 에러입니다. 문법적으로도 맞고 실행시에 아무런 문제가 발생하지 않지만 원하는 값이 안나오는 그런 에러이기 때문에 내가 구현한 로직이 잘못되어서 발생하는 에러라고 보시면 됩니다.

try...catch...finally

자바에서 쓰는 try-catch절을 자바스크립트에서도 쓸 수가 있네요
<script type="text/javascript">
<!--
try {
    // Code to run
    [break;]
} catch ( e ) {
    // Code to run if an exception occurs
    [break;]
}[ finally {
    // Code that is always executed regardless of 
    // an exception occurring
}]
//-->
</script>

 

예제:

존재하지 않는 함수를 호출할 경우 어떻게 에러가 발생하는지 한번 볼까요? 에러는 브라우저별로 다른게 보일 수 있다는 것을 명심하세요. 

<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
{
var a = 100;

alert("Value of variable a is : " + myFunc2() );

} //--> </script> </head> <body> <p>Click the following to see the result:</p> <form> <input type="button" value="Click Me" onclick="myFunc();" /> </form> </body> </html>

 

 

이제 try...catch 절을 이용해서 에러를 잡아보도록 하죠.

<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
{
   var a = 100;
   
   try {
      alert("Value of variable a is : " + myFunc2() );
   } catch ( e ) {
      alert("Error: " + e.description );
   }
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>

 

 

finally 는 try-catch절에서 에러가 발생하든 안하든 항상 실행이 되는 부분입니다.

<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
{
   var a = 100;
   
   try {
      alert("Value of variable a is : " + myFunc2()  );
   }catch ( e ) {
      alert("Error: " + e.description );
   }finally {
      alert("Finally block will always execute!" );
   }
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>

 

 

throw

throw역시 자바에 있는 개념이죠. 예외가 발생했을 때 내가 처리안하고 다른녀석한테 처리해달라고 던지는 놈입니다. throw의 사전적 의미가 "던지다" 입니다. 아래 예제를 한번 보죠.
<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
{
   var a = 100;
   var b = 0;
   
   try{
      if ( b == 0 ){
         throw( "Divide by zero error." ); 
      }else{
         var c = a / b;
      }
   }catch ( e ) {
      alert("Error: " + e );
   }
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>

 

b에 0을 할당하고 b가 0이면 throw 하도록 만든 예제네요. throw가 어떤 식으로 화면에 표현되는지 한번 실행해보세요. 

 

onerror() 메소드

 onerror 메소드는 JavaScript에서 에러핸들링을 위해서 제일 처음 나온 기능이라고 합니다.  error 이벤트는 웹페이지에서 에러가 발생했을때 window객체에서 발생시킵니다. 아래 예제를 한번 볼까요.

<html>
<head>
<script type="text/javascript">
<!--
window.onerror = function () {
   alert("An error occurred.");
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>

에러가 발생하면 경고창을 띄우도록 해놓고 존재하지 않는 함수를 호출하는 예제군요.

한번 실행해보세요. 

 

 onerror 이벤트 핸들러는 세가지 정보를 제공합니다.

  • 에러메시지 . 브라우저가 보여주는 에러메시지입니다.

  • URL . 에러가 발생한 파일을 알려줍니다.

  • 라인 넘버 . 에러를 발생시킨 라인이 몇번째 라인인지를 알려줍니다.

이 세가지 정보를 어떻게받아오는지 한번 볼까요?

<html>
<head>
<script type="text/javascript">
<!--
window.onerror = function (msg, url, line) {
   alert("Message : " + msg );
   alert("url : " + url );
   alert("Line number : " + line );
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>

 

 

 

 onerror 메소드는 아래와같이 이미지를 불러올때 에러가 발생하면 메시지를 보여주기 위해서 사용될 수도 있습니다.

<img src="myimage.gif"
    onerror="alert('An error occurred loading the image.')" />

 

이 onerror메소드는 이미지 태그 이외에도 다른 태그에서도 사용될 수 있다는 것을 알아두시면 좋을 듯 싶네요.

 

 

 

Reference : http://www.tutorialspoint.com/javascript/javascript_error_handling.htm 

 

 

 

 


Event 란?

이벤트가 뭘까요? 이벤트는 어떤 동작이라고 생각하시면 됩니다. 웹브라우저를 사용하는 사용자가 또는 웹브라우저가 어떤 동작을 하는 것을 이벤트라고 합니다. 생일파티나 축하이벤트 같은 그런 것과 혼동하시면 안됩니다 ㅋㅋㅋ

 

가장 흔하게 쓰이는 이벤트는 클릭입니다. 사용자가 어떤 버튼을 클릭하는 것. 이것도 하나의 이벤트이죠.

그럼 온클릭 이벤트에 대해서 한번 살펴볼까요? 

onclick 예제

<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
   alert("Hello World")
}
//-->
</script>
</head>
<body>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>

 

위 소스는 화면에 버튼을 하나 생성합니다. 그리고 그 버튼을 누르면 sayHello()함수를 호출하게 됩니다.

 

onsubmit 예제

onclick 이벤트 다음으로 많이 쓰이는게 아마 onsubmit이벤트일겁니다. 이 이벤트는 폼 태그에서 사용자가 submit하게 되면 발생하는 이벤트죠.

  

<html>
<head>
<script type="text/javascript">
<!--
function validation() {
   // 유효성 검사를 여기다가 하시면됩니다.
   .........
   return true  // or false
}
//-->
</script>
</head>
<body>
<form method="POST" action="t.cgi" onsubmit="return validate()">
.......
<input type="submit" value="Submit" />
</form>
</body>
</html>

 

위 소스를 분석해보면...음...submit버튼이 있고 submit버튼이 눌릴때 return validate()를 하는데 이는 validate()에서 받은 결과를 반환하겠다는 의미입니다.


onmouseover 와 onmouseout:

이 이벤트들은 마우스가 화면의 특정 지역 안에 있는지 또는 특정 지역 안에 있다가 밖으로 나갔는지를 체크하여 특정 기능을 수행할 수 있도록 도와줍니다.

예제를 한번 살펴보죠.

 

<html>
<head>
<script type="text/javascript">
<!--
function over() {
   alert("Mouse Over");
}
function out() {
   alert("Mouse Out");
}
//-->
</script>
</head>
<body>
<div onmouseover="over()" onmouseout="out()">
<h2> This is inside the division </h2>
</div>
</body>
</html>

 

마우스가 <div>태그 내의 내용물 ( 화면에 보여지는 ) 위에 있으면 over()함수를 호출하고 밖으로 나가면 out()함수를 호출합니다. 

 

HTML 4 표준 이벤트

아래는 표준 이벤트들의 목록입니다. 위에서 해본것을 바탕으로 이런저런 기능드을 한번 테스트 해보세요~~ ^___^

 

EventValueDescription
onchangescriptScript runs when the element changes
onsubmitscriptScript runs when the form is submitted
onresetscriptScript runs when the form is reset
onselectscriptScript runs when the element is selected
onblurscriptScript runs when the element loses focus
onfocusscriptScript runs when the element gets focus
onkeydownscriptScript runs when key is pressed
onkeypressscriptScript runs when key is pressed and released
onkeyupscriptScript runs when key is released
onclickscriptScript runs when a mouse click
ondblclickscriptScript runs when a mouse double-click
onmousedownscriptScript runs when mouse button is pressed
onmousemovescriptScript runs when mouse pointer moves
onmouseoutscriptScript runs when mouse pointer moves out of an element
onmouseoverscriptScript runs when mouse pointer moves over an element
onmouseupscriptScript runs when mouse button is released

 

 

 

 

Reference : http://www.tutorialspoint.com/javascript/javascript_events.htm