달력

42024  이전 다음

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

 <head>

  <title> New Document </title>

  <meta name="Generator" content="EditPlus">

  <meta name="Author" content="">

  <meta name="Keywords" content="">

  <meta name="Description" content="">

  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

<script type="text/javascript">


$(window).on('beforeunload', function(){

        return "This should create a pop-up";

    });

    </script>

 </head>


 <body>

  Windows Close Event Catch Test..

 </body>

</html>

Posted by tornado
|
출처 : http://ditio.net/2010/05/02/javascript-date-difference-calculation/


DateDiff = {
 
    inDays: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();
 
        return parseInt((t2-t1)/(24*3600*1000));
    },   inWeeks: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();
 
        return parseInt((t2-t1)/(24*3600*1000*7));
    },   inMonths: function(d1, d2) {
        var d1Y = d1.getFullYear();
        var d2Y = d2.getFullYear();
        var d1M = d1.getMonth();
        var d2M = d2.getMonth();
 
        return (d2M+12*d2Y)-(d1M+12*d1Y);
    },
 
    inYears: function(d1, d2) {
        return d2.getFullYear()-d1.getFullYear();
    }
}
 
var dString = "May, 20, 1984";
 
var d1 = new Date(dString);
var d2 = new Date();
 
document.write("<br />Number of <b>days</b> since "+dString+": "+DateDiff.inDays(d1, d2));
document.write("<br />Number of <b>weeks</b> since "+dString+": "+DateDiff.inWeeks(d1, d2));
document.write("<br />Number of <b>months</b> since "+dString+": "+DateDiff.inMonths(d1, d2));
document.write("<br />Number of <b>years</b> since "+dString+": "+DateDiff.inYears(d1, d2));
Posted by tornado
|
[URL] http://jeromebulanadi.wordpress.com/2010/03/22/scrollable-fixed-header-table-a-jquery-plugin/



Scrollable Fixed Header Table – A JQuery Plugin

March 22, 2010 at 7:51 am | Posted in JQuery | 72 Comments
Tags:
, , ,

This plugin allows html tables to be scrollable horizontally and vertically while headers are still visible and in tack with the columns. This plugin can be used in two modes:

  • With column select – Columns to view can be selected. The select state can be persisted in a named cookie.
  • Without column select

Live Demo

Demo. http://jeromebulanadi.oni.cc/scrollablefixedheader.html

With tablesorter blue theme. http://jeromebulanadi.oni.cc/sfht_sortable_blue.html

With tablesorter green theme. http://jeromebulanadi.oni.cc/sfht_sortable_green.html

Large table with 1450 rows using list-attrs plugin to improve rendering speed.  http://jeromebulanadi.oni.cc/scrollablefixedheader_big.html

Multi-row headers. http://jeromebulanadi.oni.cc/scrollablefixedheader_multirow_header.html

Download

http://plugins.jquery.com/files/sfht_1.0.1.zip

SVN repository (Latest up to date version)

Use this command to anonymously check out the latest project source code:

svn checkout http://jquery-sfht.googlecode.com/svn/trunk/ jquery-sfht-read-only

browse source codehttp://code.google.com/p/jquery-sfht/source/browse

view change listhttp://code.google.com/p/jquery-sfht/source/list

Dependencies

Getting Started

1. Import dependencies

<link href="css/scrollableFixedHeaderTable.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="javascripts/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="javascripts/jquery.cookie.pack.js"></script>
  
<script type="text/javascript" src="javascripts/jquery.dimensions.min.js"></script>
<script type="text/javascript" src="javascripts/jquery.scrollableFixedHeaderTable.js"></script>

2. HTML Table. As of this version the following rules must be followed to make the plugin work.

  • The table should have an id attribute.
  • The table should be decorated with CSS class name. It does not work well with css id or style attribute yet.
  • The table’s class attribute should have “scrollableFixedHeader” as one of the values.

Here’s the sample table. The highlighted line applies the rule above.

<style>
    .myTable {
        background-color: BLACK;
    }
  
    .myTable td {
        background-color: WHITE;
    }
  
  .myTable .header td {
    font-weight: bold;
    background-color: #CCCCCC;
  }
</style>
  
<table id="table1" class="myTable scrollableFixedHeaderTable" width="600px" cellspacing="1">
  <tr class="header">
    <td>Header1</td><td>Header2</td><td>Header3</td><td>Header4</td>
  </tr>
  <tr>
    <td>cell (1, 1)</td><td>cell (2, 1)</td><td>cell (3, 1)</td><td>cell (4, 1)</td>
  </tr>
  <tr>
    <td>cell (1, 2)</td><td>cell (2, 2)</td><td>cell (3, 2)</td><td>cell (4, 2)</td>
  </tr>
  <tr>
    <td>cell (1, 3)</td><td>cell (2, 3)</td><td>cell (3, 3)</td><td>cell (4, 3)</td>
  </tr>
  <tr>
    <td>cell (1, 4)</td><td>cell (2, 4)</td><td>cell (3, 4)</td><td>cell (4, 4)</td>
  </tr>
  <tr>
    <td>cell (1, 5)</td><td>cell (2, 5)</td><td>cell (3, 5)</td><td>cell (4, 5)</td>
  </tr>

3. Call the plugin function.

$(document).ready(function(){
    $('#table1').scrollableFixedHeaderTable(300,100,'true','scr_table_1_');
});

Usage

With column select . Selected columns remained after page reload.

$(tableID).scrollableFixedHeaderTable(widthpx, heightpx, showSelect, cookie);

With column selectAll columns are restored after page reload.

$(tableID).scrollableFixedHeaderTable(widthpx, heightpx, showSelect);

Without column select

$(tableID).scrollableFixedHeaderTable(widthpx, heightpx);

Multirow headers

$(tableID).scrollableFixedHeaderTable(widthpx, heightpx, null, null, rowCount);

Arguments

  • tableID – ID of the table to transform
  • widthpx – width in pixels of the transformed table
  • heightpx – height in pixels of the transformed table
  • showSelect – When true, shows a blue arrow on top
  • cookie – cookie where the selected state of the column select will be stored.
  • rowCount - number of header rows

Multi-row Headers

Reference from #comment-83.

Using column select only works if there are no rowspans and colspans as there is no easy way to map the header’s tr tag index to the group of tr tags in the data that is why I placed null on the column select parameters.

$(tableID).scrollableFixedHeaderTable(widthpx, heightpx, null, null, rowCount);

The row count parameters determines the number of rows from the top to be used as a header.

While version 1.0.2 is not released yet, you can download the latest source from the trunk.

Get the latest trunk source jquery.scrollableFixedHeaderTable.js

Here’s the live demo.

http://jeromebulanadi.oni.cc/scrollablefixedheader_multirow_header.html

Improve Table Transformation Speed

By default, the plugin extracts the header using the easy way:

$(sourceTable).clone().find('tr:gt(0)').remove();

That line of code creates a copy of the source table then reduces that copy to headers only. This may be good for small tables but not for very big tables. see #comment-62.

For speed improvement, get the latest plugin version, and list-attrs plugin.

Here are the links

jquery.scrollableFixedHeaderTable.js

jquery-list-attributes.js

Add the a Document type to your page to force IE 8 to render in standards mode.

example:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

Add the listAttributes plugin to your scripts.

<script type="text/javascript" src="javascripts/jquery-list-attributes.js"></script>

You may clear your cache of the of sfht plug in.

That’s all! The latest sfht plugin will use grab only the header when the listAttrs plugin is detected.

Here’s a live demo with a table containing 1450 rows.  The page transforms the table after the document loads in a short time.

http://jeromebulanadi.oni.cc/scrollablefixedheader_big.html

Integrating with JQuery Tablesorter

You can view live the the demo here:

blue theme. http://jeromebulanadi.oni.cc/sfht_sortable_blue.html

green theme. http://jeromebulanadi.oni.cc/sfht_sortable_green.html

or offline with the sfth_1.0.1 release. sfht_sortable_blue.html and sfth_sortable_green.html

Tablesorter is great jQuery plugin for sorting data with a click on the header.  Integration with this plugin have a few changes, however.

1. The table should have in this tag order:

<table>
  <thead>
    <tr>
      <th>...</th>
      ...
    </tr>
    ...
  </thead>
  <tbody>
    <tr>
      <td>...</td>
      ...
    </tr>
    ...
  </tbody>
</table>

Yes, th for header and td for data.

2. Remove the width, border and padding from table.tablesorter class from the selected table sorter theme. This ensures compatibility with browser box models. This example is from themes\blue\styles.css of the tablesorter package.

table.tablesorter {
  font-family:arial;
  background-color: #CDCDCD;
  /* margin:10px 0pt 15px; */
  font-size: 8pt;
  /* width: 100%; */
  text-align: left;
}

The modifications are ready, you can add this imports from table sorter.

<link href="css/themes/blue/style.css" rel="stylesheet"  type="text/css" />
<script type="text/javascript" src="javascripts/jquery.tablesorter.js"></script>

Now,  for the initializing script.

$(document).ready(function(){
    $('#myTable1').scrollableFixedHeaderTable(800, 200, true, 'mycookie');
    $('#myTable1').tablesorter().bind('sortEnd', function(){
        var $cloneTH = $('.sfhtHeader thead th');
        var $trueTH = $('.sfhtData thead th');
        $cloneTH.each(function(index){
            $(this).attr('class', $($trueTH[index]).attr('class'));
        });
    });

    /* synchronize sortable and scrollable */
    $('.sfhtHeader thead th').each(function(index){
        var $cloneTH = $(this);
        var $trueTH = $($('.sfhtData thead th')[index]);
        $cloneTH.attr('class', $trueTH.attr('class'));
        $cloneTH.click(function(){
            $trueTH.click();
        });
    });
});

If your are using the green theme. Use spaces as padding for the headers. The script below adds 10 spaces to each header.

$('th.header').each(function(){
  var $this = $(this);
  var spaced = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'
  + $(this).html();
  $this.html(spaced);
});

The multisort feature, using shift key, does not work by clicking on the floating header.

It may be possible by means of programmatic multisorting instead of using the original click event.

Posted by tornado
|

[link] http://jquery.malsup.com/block/#element

select box 나 TextArea 등에 DIV를 올릴 경우 제대로 가려주는 플러그인.

ActiveX 도 잘 가려집니다.

참고 그림.



Posted by tornado
|
Posted by tornado
|

[출처] http://stackoverflow.com/questions/832860/how-to-scroll-the-window-using-jquery-scrollto-function

 

 

Hi,

I'm trying to scroll down 100px every time the user gets near the top of the document.

I have the function executing when the user gets close to the top of the document, but the .scrollTo function isn't working.

I put an alert after and before to check to see if it actually was the line or not that was stopping it and only the first alert goes off, here's the code:

alert("starting"); 
$.scrollTo({ top: '+=100px', left: '+=0px' }, 800); 
alert("finished"); 

I know I have the jquery page linked properly because I'm using many other jquery functions throughout and they all work fine. I've also tried removing the 'px' from above and it doesn't seem to make a difference.

flag
Don't you have a JavaScript debugger? – Matthew Flaschen May 7 at 4:17
1  
Jquery itself my be working fine, but are you sure you have the scrollTo plugin linked properly? Change one of those alerts to alert($.scrollTo); – Andrew May 7 at 5:03

2 Answers

vote up 6 vote down check

If it's not working why don't you try using jQuery's scrollTop method?

$("#id").scrollTop($("#id").scrollTop() + 100); 

If you're looking to scroll smoothly you could use basic javascript setTimeout/setInterval function to make it scroll in increments of 1px over a set length of time.

'DHTML > Javascript' 카테고리의 다른 글

jquery block ui.....  (0) 2010.08.06
[jquery] AD-Gallery Image Slider...  (0) 2010.03.17
[펌] HTML 객체의 절대 좌표 구하기.  (0) 2009.09.25
JQuery 로 시간을 선택한다. TimePicker 2종류  (0) 2009.09.03
http://visualjquery.com/  (0) 2009.08.05
Posted by tornado
|


출처 : http://blog.naver.com/devstory/130038823596



 

객체의 좌표 값 추출

 

익스플로러 6 / 파이어폭스 2 에서 테스트 되었습니다.

 

<HTML>
<HEAD>
 <SCRIPT type = "text/javascript">
  /**
   * 좌표 값을 측정한다.
   *
   * @param obj 측정 요망 객체
   */
  function getBounds( obj ) {
   var ret = new Object();

   if(document.all) {
    var rect = obj.getBoundingClientRect();
    ret.left = rect.left + (document.documentElement.scrollLeft || document.body.scrollLeft);
    ret.top = rect.top + (document.documentElement.scrollTop || document.body.scrollTop);
    ret.width = rect.right - rect.left;
    ret.height = rect.bottom - rect.top;
   } else {
    var box = document.getBoxObjectFor(obj);
    ret.left = box.x;
    ret.top = box.y;
    ret.width = box.width;
    ret.height = box.height;
   }

   return ret;
  }

  /**
   * 버튼 객체의 좌표 추출
   */
  function getThisCoordi() {
   var obj = getBounds( document.getElementById("testBtn") );

   alert( "left : " + obj.left + ", top : " + obj.top + ", width : " + obj.width + ", height : " + obj.height );
  }
 </SCRIPT>
</HEAD>
<BODY>
<P>&nbsp;</P>
<CENTER><INPUT type = "button" id = "testBtn" value = "테스트" onClick = "getThisCoordi()"/></CENTER>
</BODY>
</HTML>

Posted by tornado
|
Jquery 에 달력만 있는줄 알았는데, 시간 선택하는 녀석도 있었습니다.

목마른 놈이 우물 판다더니... 덕분에 일 하나 주워 먹었다~


첫번째 :

[출처] http://www.jnathanson.com/index.cfm?page=jquery/clockpick/ClockPick#config

BGIFramework 라는 js 를 제공해 주는데, 이것을 같이 쓰면 CheckBox 같은것에 겹쳐지지 않는다.

UI 적으로는 아주 좋지는 않지만 쓰기에는 편리함.



두번째 :

[출처] http://haineault.com/media/jquery/ui-timepickr/page/#d-demo-wrapper-1

요거는 모양도 이쁘고, 테마도 지원된다.

SelectBox, CheckBox 등이 있으면 겹쳐지는 문제가 발생.

고치려고 하니, Jquery 초보라 힘듬 -.-;








Posted by tornado
|

출처 : http://onlybible.tistory.com/entry/jquery-visual-하게-공부하기-ok



http://visualjquery.com/ 



Posted by tornado
|
출처 : http://www.ibm.com/developerworks/kr/library/x-ajaxjquery.html


jQuery로 Ajax 개발을 단순화 하기

Ajax와 DOM 스크립팅을 쉽게 하는 방법

developerWorks
문서 옵션
수평출력으로 설정

이 페이지 출력

이 페이지를 이메일로 보내기

이 페이지를 이메일로 보내기

영어원문

영어원문


제안 및 의견
피드백

난이도 : 중급

Jesse Skinner, Web Developer, Freelance

2007 년 9 월 04 일

jQuery는 JavaScript 라이브러리로서 JavaScript™와 Asynchronous JavaScript + XML (Ajax) 프로그래밍을 단순화 하는데 도움이 됩니다. JavaScript 라이브러리와는 달리, jQuery는 복잡한 코드를 간결하게 표현할 수 있는 독특한 철학이 있습니다. jQuery 원리, 기능과 특징을 배우고, 일반적인 Ajax 태스크도 수행하며, 플러그인으로 jQuery를 확장하는 방법도 알아봅니다.

jQuery란 무엇인가?

2006년 초, John Resig가 만든 jQuery는 JavaScript 코드로 작업하는 사람들에게는 훌륭한 라이브러리이다. 여러분이 JavaScript 언어 초보자라서 라이브러리가 Document Object Model (DOM) 스크립팅과 Ajax의 복잡성을 다루어주기를 원하든지, 숙련된 JavaScript 구루로서 DOM 스크립팅과 Ajax의 반복성에 지루해졌다면, jQuery가 제격이다.

jQuery는 코드를 단순하고 간결하게 유지한다. 많은 반복 루프와 DOM 스크립팅 라이브러리 호출을 작성할 필요가 없다. jQuery를 사용하면 매우 적은 문자로 표현할 수 있다.

jQuery 철학은 매우 독특하다. 무엇이든 단순하고 재사용 가능한 것으로 유지하기 위해 디자인 되었다. 여러분이 이러한 철학을 이해하고 여기에 편안함을 느낀다면, jQuery가 여러분의 프로그래밍 방식을 충분히 향상시킬 수 있다.




위로


단순화

다음은 jQuery가 여러분의 코드에 어떤 영향을 미치는지를 보여주는 예제이다. 페이지의 모든 링크에 클릭 이벤트를 붙이는 것 같이 단순하고 일반적인 것을 수행하려면, 플레인 JavaScript 코드와 DOM 스크립팅을 사용하는 것이 낫다. (Listing 1)


Listing 1. jQuery 없는 DOM 스크립팅
                
var external_links = document.getElementById('external_links');
var links = external_links.getElementsByTagName('a');
for (var i=0;i < links.length;i++) {
    var link = links.item(i);
    link.onclick = function() {
        return confirm('You are going to visit: ' + this.href);
    };
}

Listing 2는 같은 기능에 jQuery를 사용한 모습이다.


Listing 2. jQuery를 사용한 DOM 스크립팅
                
$('#external_links a').click(function() {
    return confirm('You are going to visit: ' + this.href);
});

놀랍지 않은가? jQuery를 사용하면 복잡하지 않게 코드로 표현하고자 하는 것만 나타낼 수 있다. 엘리먼트를 반복할 필요가 없다. click() 함수가 이 모든 것을 관리한다. 또한, 다중 DOM 스크립팅 호출도 필요 없다. 여기에서 필요한 것은 엘리먼트가 어떻게 작동하는지를 설명하는 짧은 스트링이다.

이 코드로 어떻게 작업이 수행되는지를 이해하기는 조금 어렵다. 우선, $() 함수가 있어야 한다. 이것은 jQuery에서 가장 강력한 함수이다. 대게, 이 함수를 사용하여 문서에서 엘리먼트를 선택한다. 이 예제에서, 이 함수는 Cascading Style Sheets (CSS) 신택스를 포함하고 있는 스트링으로 전달되고, jQuery는 효율적으로 이 엘리먼트를 찾는다.

CSS 셀렉터의 기본을 이해하고 있다면, 이 신택스가 익숙할 것이다. Listing 2에서, #external_linksexternal_linksid를 가진 엘리먼트를 찾는다. a 앞에 있는 공간은 jQuery에게 external_links 엘리먼트 내의 모든 <a> 엘리먼트를 찾도록 명령한다. 영어와 DOM은 장황하지만, CSS에서는 매우 간단하다.

$() 함수는 CSS 셀렉터와 매치하는 모든 엘리먼트를 포함하고 있는 jQuery 객체를 리턴한다. jQuery 객체는 어레이와 비슷하지만, 수 많은 특별한 jQuery 함수들이 포함된다. 예를 들어, click 함수를 호출함으로써 클릭 핸들러 함수를 jQuery 객체의 각 엘리먼트에 할당할 수 있다.

또한, 엘리먼트나 엘리먼트의 어레이를 $() 함수로 전달하면, 이것은 엘리먼트 주위에 jQuery 객체를 래핑할 것이다. 이 기능을 사용하여 window 객체 같은 것에 jQuery 함수를 적용하고 싶을 것이다. 일반적으로 이 함수를 다음과 같이 로드 이벤트에 할당한다.

window.onload = function() {
    // do this stuff when the page is done loading
};

jQuery를 사용하면, 같은 코드도 다음과 같이 된다.

$(window).load(function() {
    // run this when the whole page has been downloaded
});

이미 알고 있었겠지만, 윈도우가 로딩하기를 기다리는 일은 매우 지루한 일이다. 전체 페이지가 로딩을 끝마쳐야 하기 때문이다. 여기에는 페이지의 모든 이미지들도 포함된다. 가끔, 이미지 로딩을 먼저 끝내고 싶지만, 대부분의 경우 Hypertext Markup Language (HTML)만 로딩해야 한다. jQuery는 문서에 특별한 ready 이벤트를 만듦으로써 이 문제를 해결한다.

$(document).ready(function() {
    // do this stuff when the HTML is all ready
});

이 코드는 document 엘리먼트 주위에 jQuery 객체를 만들고, HTML DOM 문서가 준비될 때 함수를 설정하여 인스턴스를 호출한다. 이 함수를 필요한 만큼 호출할 수 있다. 진정한 jQuery 스타일에서, 지름길은 이 함수를 호출하는 것이다. 함수를 $() 함수로 전달한다.

$(function() {
    // run this when the HTML is done downloading
});

지금까지, $() 함수를 사용하는 세 가지 방법을 설명했다. 네 번째 방법은, 스트링을 사용하여 엘리먼트를 만드는 것이다. 결과는, 그 엘리먼트를 포함하고 있는 jQuery 객체가 된다. Listing 3은 문단을 페이지에 추가하는 예제이다.


Listing 3. 간단한 문단을 생성하여 붙이기
                
$('<p></p>')
    .html('Hey World!')
    .css('background', 'yellow')
    .appendTo("body");

이전 예제에서 파악했겠지만, jQuery의 또 다른 강력한 기능은 메소드 체인(method chaining.)이다. jQuery 객체에 대해 메소드를 호출할 때마다, 이 메소드는 같은 jQuery 객체를 리턴한다. jQuery 객체에 다중 메소드를 호출하고 싶다면 셀렉터를 다시 입력하지 않고 이를 수행할 수 있다.

$('#message').css('background', 'yellow').html('Hello!').show();




위로


Ajax로 단순하게!

Ajax는 jQuery를 사용하면 더 단순해 질 수 있다. jQuery에는 쉬운 것도 쉽게 복잡한 것도 가능한 단순하게 만드는 유용한 함수들이 많이 있다.

Ajax에서 사용되는 방식은 HTML 청크를 페이지 영역에 로딩하는 것이다. 여러분이 필요로 하는 엘리먼트를 선택하고 load() 함수를 사용하는 것이다. 다음은 통계를 업데이트 하는 예제이다.

$('#stats').load('stats.html');

일부 매개변수들을 서버 상의 페이지로 전달해야 할 경우가 종종 있다. jQuery를 사용하면 이는 매우 간단하다. 필요한 메소드가 어떤 것인지에 따라서 $.post()$.get() 중 선택한다. 선택적 데이터 객체와 콜백 함수를 전달할 수도 있다. Listing 4는 데이터를 보내고 콜백을 사용하는 예제이다.


Listing 4. Ajax를 사용하여 데이터를 페이지로 보내기
                
$.post('save.cgi', {
    text: 'my string',
    number: 23
}, function() {
    alert('Your data has been saved.');
});

복잡한 Ajax 스크립팅을 해야 한다면, $.ajax() 함수가 필요하다. xml, html, script, json을 지정할 수 있고, 여러분이 바로 사용할 수 있도록 jQuery가 자동으로 콜백 함수에 대한 결과를 준비한다. 또한, beforeSend, error, success, complete 콜백을 지정하여 사용자에게 Ajax에 대한 더 많은 피드백을 제공할 수 있다. 게다가, Ajax 요청의 타임아웃이나 페이지의 "최종 변경" 상태를 설정하는 매개변수들도 있다. Listing 5는 필자가 언급했던 매개변수를 사용하여 XML 문서를 검색하는 예제이다.


Listing 5. $.ajax()를 사용하여 복잡한 Ajax를 단순하게
                
$.ajax({
    url: 'document.xml',
    type: 'GET',
    dataType: 'xml',
    timeout: 1000,
    error: function(){
        alert('Error loading XML document');
    },
    success: function(xml){
        // do something with xml
    }
});

콜백 성공으로 XML을 받으면, jQuery를 사용하여 HTML에서 했던 것과 같은 방식으로 XML을 볼 수 있다. 이는 XML 문서 작업을 쉽게 하며 콘텐트와 데이터를 웹 사이트로 쉽게 통합시킨다. Listing 6은 리스트 아이템을 XML의 <item> 엘리먼트용 웹 페이지에 추가하는 success 함수에 대한 확장 모습이다.


Listing 6. jQuery를 사용하여 XML 작업하기
                
success: function(xml){
    $(xml).find('item').each(function(){
        var item_text = $(this).text();

        $('<li></li>')
            .html(item_text)
            .appendTo('ol');
    });
}




위로


HTML 애니메이션

jQuery를 사용하여 기본적인 애니메이션과 효과를 다룰 수 있다. 애니메이션 코드의 중심에는 animate() 함수가 있는데, 이는 숫자로 된 CSS 스타일 값을 바꾼다. 예를 들어, 높이, 넓이, 폭, 위치를 움직일 수 있다. 또한, 애니메이션의 속도를 밀리초 또는 사전 정의된 속도(느림, 보통, 빠름)로 지정할 수 있다.

다음은, 엘리먼트의 높이와 넓이를 동시에 움직이게 하는 예제이다. 시작 값은 없고 종료 값만 있다. 시작 값은 엘리먼트의 현재 크기에서 가져온다. 여기에도 콜백 함수를 첨부했다.

$('#grow').animate({ height: 500, width: 500 }, "slow", function(){
    alert('The element is done growing!');
});

jQuery는 빌트인 함수를 사용하여 일반적인 애니메이션도 더욱 쉽게 만든다. show()hide() 엘리먼트를 즉각적으로 또는 지정된 속도로 사용할 수 있다. fadeIn()fadeOut() 또는 slideDown()slideUp()을 사용하여 엘리먼트를 나타나게 하거나 사라지게 할 수 있다. 다음은 네비게이션의 slidedown 예제이다.

$('#nav').slideDown('slow');




위로


DOM 스크립팅과 이벤트 핸들링

jQuery는 DOM 스크립팅과 이벤트 핸들링을 단순화하는데 제격이다. DOM의 트래버스와 조작이 쉽고, 이벤트의 첨부, 제거, 호출은 매우 자연스러운 일이며, 직접 수행하는 것보다 에러도 적게 발생한다.

기본적으로 jQuery는 DOM 스크립팅으로 수행하는 일들을 더욱 쉽게 수행할 수 있도록 해준다. 엘리먼트를 생성하고 append() 함수를 사용하여 이들을 다른 엘리먼트로 연결할 수 있고, clone()을 사용하여 엘리먼트를 중복시키고, 콘텐트를 html()로 설정하고, empty() 함수로 콘텐트를 삭제하고, remove() 함수로 엘리먼트를 삭제하고, wrap() 함수를 사용하여 또 다른 엘리먼트로 엘리먼트를 래핑한다.

DOM을 트래버스 함으로써 jQuery 객체의 콘텐트를 변경할 때 여러 함수들을 사용할 수 있다. 엘리먼트의 siblings(), parents(), children()을 사용할 수 있다. 또한, next() 또는 prev() sibling 엘리먼트도 선택할 수 있다. 아마도 가장 강력한 것은 find() 함수일 것이다. jQuery 셀렉터를 사용하여 jQuery 객체의 엘리먼트 종속 관계들을 통해 검색할 수 있다.

이 함수는 end() 함수와 사용될 때 더욱 강력해진다. 이 함수는 실행 취소 함수와 비슷하고, find() 또는 parents() 또는 다른 트래버싱 함수들을 호출하기 전에 가졌던 jQuery 객체로 돌아간다.

메소드 체인과 함께 사용되면, 복잡한 연산도 단순하게 보이게 할 수 있다. Listing 7은 로그인 폼을 찾고 이와 관련한 여러 엘리먼트를 조작하는 예제이다.


Listing 7. DOM의 트래버스와 조작
                
$('form#login')
    // hide all the labels inside the form with the 'optional' class
    .find('label.optional').hide().end()

    // add a red border to any password fields in the form
    .find('input:password').css('border', '1px solid red').end()

    // add a submit handler to the form
    .submit(function(){
        return confirm('Are you sure you want to submit?');
    });

믿을 수 있는지 모르겠지만, 이 예제는, 공백을 사용한 하나의 연결된 코드 라인일 뿐이다. 우선, 로그인 폼을 선택했다. 그리고 나서, 이 안에 선택 레이블을 찾고, 이들을 숨긴 다음, end()를 호출하여 폼으로 돌아가게 하였다. 패스워드 필드를 찾았고, 보더를 빨간색으로 한 다음, 다시 end()를 호출하여 폼으로 돌아갔다. 마지막으로, 제출 이벤트 핸들러를 폼에 추가했다. 여기에서 특히 재미있는 부분은 jQuery가 모든 쿼리 연산들을 최적화 하기 때문에, 여러분은 모든 것이 서로 잘 연결될 때 엘리먼트를 두 번 찾을 필요가 없다.

공통 이벤트 핸들링은 click(), submit(), mouseover() 같은 함수를 호출하고 여기에 이벤트 핸들러 함수를 전달하는 것만큼 단순하다. 게다가, bind('eventname', function(){})을 사용하여 커스텀 이벤트 핸들러를 할당하는 옵션도 있다. unbind('eventname')를 사용하여 특정 이벤트를 제거하거나, unbind()를 사용하여 모든 이벤트를 제거할 수 있다. 이것과 기타 함수들을 사용하는 다른 방법들은, jQuery 애플리케이션 프로그램 인터페이스(API) 문서를 참조하라. (참고자료)




위로


jQuery 셀렉터의 힘 활용하기

#myid 같은 아이디 또는 div.myclass 같은 클래스 이름으로 엘리먼트를 선택한다. 하지만, jQuery는 하나의 셀렉터에서 거의 모든 엘리먼트 조합을 선택할 수 있도록 하는 복잡하고도 완벽한 셀렉터 신택스를 갖고 있다.

jQuery의 셀렉터 신택스는 CSS3과 XPath에 기반하고 있다. CSS3과 XPath 신택스를 더욱 잘 안다면, jQuery 사용이 더욱 수월해진다. CSS와 XPath를 포함하여 jQuery 셀렉터의 전체 리스트를 보려면 참고자료 섹션을 참조하라.

CSS3에는 모든 브라우저가 지원하지 않는 신택스가 포함되어 있기 때문에, 이를 자주 볼 수 없다. 하지만, jQuery에서 CSS3을 사용하여 엘리먼트를 선택한다. jQuery는 고유의 커스텀 셀렉터 엔진을 갖고 있다. 예를 들어, 테이블의 모든 빈 컬럼 안에 대시(dash)를 추가하려면, :empty pseudo-selector를 사용한다.

$('td:empty').html('-');

특정 클래스를 갖고 있지 않은 모든 엘리먼트를 찾는다면? CSS3은 이를 위한 신택스도 있다. :not pseudo-selector를 사용하는 것이다. 다음은 required의 클래스를 갖고 있지 않은 모든 인풋을 숨기는 방법이다.

$('input:not(.required)').hide();

또한, CSS에서처럼 다중 셀렉터를 콤마를 사용하여 하나로 연결시킬 수 있다. 다음은 이 페이지에서 모든 리스트 유형들을 동시에 숨기는 예제이다.

$('ul, ol, dl').hide();

XPath는 하나의 문서에서 엘리먼트를 찾는 강력한 신택스이다. CSS와는 다르며, CSS로 수행할 수 없는 몇 가지 일을 수행할 수 있다. 보더를 모든 체크 박스의 부모 엘리먼트에 추가하려면, XPath의 /.. 신택스를 사용할 수 있다.

$("input:checkbox/..").css('border', '1px solid #777');

가독성 있는 테이블을 만들려면, 다른 클래스 이름을 테이블의 모든 짝수 또는 홀수 행에 붙인다. 이를 다른 말로 테이블의 스트라이핑(striping)이라고 한다. jQuery를 사용하면 :odd pseudo-selector 덕택에 쉽게 수행할 수 있다. 아래 예제는 테이블의 모든 홀수 행의 백그라운드를 striped 클래스를 사용하여 변경한다.

$('table.striped > tr:odd').css('background', '#999999');

jQuery 셀렉터로 코드를 어느 정도 단순화 할 수 있는지를 보았다. 어떤 엘리먼트를 선택하든지 간에, 하나의 jQuery 셀렉터를 사용하여 이를 정의하는 방법도 찾을 수 있다.




위로


플러그인으로 jQuery 확장하기

대부분의 소프트웨어와는 달리, jQuery용 플러그인 작성은 복잡한 API를 사용해야 하는 힘든 일이 아니다. 사실, jQuery 플러그인은 작성하기가 쉬워서 몇 가지만 작성하면 코드를 더욱 단순하게 유지할 수 있다. 다음은 여러분이 작성할 수 있는 가장 기본적인 jQuery 플러그인이다.

$.fn.donothing = function(){
    return this;
};

단순하지만, 이 플러그인은 약간의 설명이 필요하다. 우선, 함수를 모든 jQuery 객체에 추가하려면, 여기에 $.fn을 할당하고, 이 함수는 this (jQuery 객체)를 리턴하여 이것이 메소드 체인을 깨트리지 않도록 해야 한다.

이 예제를 기반으로 쉽게 구현할 수 있다. css('background')를 사용하는 대신 플러그인을 작성하여 백그라운드를 바꾸려면, 다음을 사용한다.

$.fn.background = function(bg){
    return this.css('background', bg);
};

css()에서 값을 리턴할 뿐이다. 이것은 이미 jQuery 객체를 리턴하기 때문이다. 따라서, 메소드 체인은 여전이 잘 작동한다.

여러분은 반복 작업이 있을 경우에 jQuery 플러그인을 사용하기 바란다. 예를 들어, 같은 일을 여러 번 수행하기 위해 each() 함수를 사용하고 있다면 플러그인을 사용해도 된다.

jQuery 플러그인을 작성이 쉽기 때문에, 여러분이 사용할 수 있는 것도 수백 가지나 존재한다. jQuery는 탭, 곡선형 코너, 슬라이드 쇼, 툴 팁, 날짜 셀렉터, 기타 여러분이 상상하고 있는 모든 것을 위한 플러그인이 있다. 플러그인 리스트는 참고자료 섹션을 참조하기 바란다.

가장 복잡하고 광범위하게 사용되는 플러그인은 Interface이다. 이것은 정렬, 드래그&드롭 기능, 복합 효과, 기타 복잡한 사용자 인터페이스(UI)를 핸들하는 애니메이션 플러그인이다. Interface가 jQuery를 위한 것이라면 Prototype에는 Scriptaculous가 있다.

또한 Form 플러그인도 대중적이고 유용하다. 이것으로 Ajax를 사용하여 백그라운드에서 폼을 쉽게 제출할 수 있다. 이 플러그인은 폼의 제출 이벤트를 하이재킹 하고, 다른 인풋 필드를 찾고, 이들을 사용하여 Ajax 호출을 구현하는 상황에 사용된다.




위로


jQuery 이후의 삶

jQuery를 사용하여 할 수 있는 것의 표면적인 부분만 다루었다. jQuery는 기분 좋게 사용할 수 있고 새로운 트릭이나 기능도 자연스럽다. jQuery는 JavaScript와 Ajax 프로그래밍을 매우 단순화 시킬 수 있다. 새로운 것을 배울 때마다 코드는 더욱 단순해 진다.

jQuery를 배운 후에, 필자는 JavaScript 언어로 하는 프로그래밍에 재미를 발견했다. 지루한 부분은 알아서 처리되기 때문에, 필자는 중요한 코딩 부분에만 집중하면 된다. jQuery를 사용하게 되면서 지난날 for 루프를 작성하던 때는 거의 기억이 나지 않는다. 심지어, 다른 JavaScript 라이브러리를 사용할 생각도 거의 하지 않는다. jQuery는 JavaScript 프로그래밍 방식을 진정으로 바꿔 놓았다.



참고자료

교육

제품 및 기술 얻기

토론


필자소개

Photo of Jesse Skinner

Jesse Skinner는 JavaScript와 CSS 전문 프리랜스 웹 개발자이다. 캐나다와 독일이 주 활동 무대이며, CSS 브라우저 호환성 미스터리를 풀고 있다. Jesse에 대해 더욱 알고 싶거나 웹 개발에 대한 글을 더 읽고 싶다면, 블로그 The Future of the Web를 방문해 보라.



Posted by tornado
|
출처 : http://www.ibm.com/developerworks/kr/library/wa-jquery3/



jQuery로 작업하기, 3부: jQuery와 Ajax로 RIA 만들기: JQuery: 내일 나올 웹 응용을 오늘 구현해보자

Effects 모듈과 Ajax

developerWorks
문서 옵션
수평출력으로 설정

이 페이지 출력

이 페이지를 이메일로 보내기

이 페이지를 이메일로 보내기

샘플 코드

영어원문

영어원문


제안 및 의견
피드백

난이도 : 중급

Michael Abernethy, 제품 개발 관리자, Optimal Auctions

옮긴이 : 박재호 이해영 dwkorea@kr.ibm.com

원문 게재일 : 2008 년 10 월 28 일
번역 게재일 : 2009 년 1 월 13 일

JQuery는 동적 RIA를 쉽게 개발하는 방법에 목마른 개발자를 위한 자비스크립트 라이브러리로 각광을 받고 있습니다. 브라우저 기반 응용이 데스크톱 응용을 계속 대체하고 있기에, 이런 라이브러리 활용 역시 꾸준히 증가 추세에 있습니다. jQuery 연재물에서 jQuery로 웹 응용 프로젝트를 구현하는 방법을 살펴봅시다.

도입

jQuery는 지난 몇 개월 동안에 웹 개발자를 위한 유력한 자바스크립트 라이브러리로 급속도로 세를 넓혀가고 있다. 이런 현상은 브라우저 기반 응용으로 데스크톱 응용을 교체하기 위한 RIA(Rich Internet Application) 활용과 필요성이 급격하게 늘어나는 상황과 맞물려 돌아간다. 스프레드시트부터 급여 계산에서 전자편지 응용에 이르기까지 브라우저로 데스크톱 응용을 교체해 나가는 현실이다. 이런 응용 개수가 많아지고 복잡해지면서 자바스크립트 라이브러리는 응용을 만드는 튼튼한 기초로 더욱 더 중요성이 높아질 것이다. jQuery는 개발자를 위한 필수 라이브러리가 되었다. 이 연재물에서는 jQuery를 깊숙하게 탐험하며, 개발자가 RIA를 빠르고 쉽게 만들기 위한 튼튼한 토대를 제공한다.

직전 기사에서 RIA를 만드는 세 가지 기본 구성 요소와 페이지에 상호 작용을 추가하는 방법을 배웠다. 첫 번째로 살펴본 Event 모듈은 페이지에서 사용자가 일으킨 사건을 잡아서 프로그램 상에서 반응하도록 만들었다. 이런 기능을 사용해 버튼 누르기, 마우스 이동과 같은 사용자 행동 처리용 코드를 붙인다. 다음으로 살펴본 Attributes 모듈은 페이지 엘리먼트에서 값을 얻고 엘리먼트에 값을 설정하는 방법과 변수값을 포함한 자료 객체로 취급하는 방법을 설명했다. 이런 변수값은 사용자에게 어떤 반응을 보일지 결정하는 과정에 필요한 정보 대다수를 포함한다. 마지막으로 CSS 조작 방법을 살펴보고 페이지를 다시 읽어들이지 않고서도 배치, 색상, 글꼴 등을 변경하는 방법을 익혔다. 이런 세 가지 모듈에 익숙해지면, 상호대화식 웹 페이지를 구성하는 세 가지 기초 구성 요소를 익힌 셈이다. 사용자 반응을 잡아(Event), 정보를 획득하고(Attributes), 사건과 정보를 조합한 내용을 토대로 피드백을 제공한다(CSS).

이 기사에서 동적인 웹 페이지를 구성하는 세 가지 기본 요소를 사용한다. 이런 요소는 오늘날 볼 수 있는 좀 더 첨단 웹 응용의 일부로 자리잡은 "화끈한" 효과와 기능을 제공한다. 추가 모듈이 RIA에 핵심은 아니지만, 사용자가 기억할 만한 추가 기능을 제공하며 RIA에서 사용 가능한 범위와 기능을 엄청나게 넓혀준다. 살펴볼 첫 모듈은 Effects 모듈로 엘리먼트 감추기, 엘리먼트 이동, 페이드 인/아웃과 같은 기능을 포함한다. 다시 말해 웹 페이지를 화끈하게 만드는 기능이다. 이 기사에서 설명하는 마지막 모듈은 비동기식 자바스크립트 + XML(Ajax) 모듈이다. Ajax는 RIA 하면 가장 먼저 떠오르는 단어다. Ajax는 웹 응용에 서버와 통신하는 능력을 부여해 페이지를 다시 읽어들이지 않고서도 정보를 전달하고 인출하는 기능을 제공한다(웹에 떠도는 잘못된 의견과는 달리 AJax는 단순히 멋진 자바스크립트 애니메이션 기능은 아니다). jQuery가 믿기 어려울 정도로 손쉬운 AJax 도구를 제공하며, 실제로 Ajax 사용을 자바스크립트 메서드 호출 수준으로 단순하게 만들어준다.

이 기사에서 소개하는 예제 응용은 Effects와 Ajax 모듈을 데모 웹 응용인 웹 메일로 집어넣는 방법을 보여주면서 끝을 맺는다. 몇 가지 Effects를 데모에 추가해 활력을 불어넣고, 더욱 중요하게 몇 가지 Ajax 코드를 추가해 웹 메일이 페이지를 다시 읽지 않고서도 메시지를 출력하도록 만든다.

Effects

Effects 모듈은 이름처럼 "심각한" 웹 페이지가 회피해야 하는 애니메이션과 특수 효과만 포함한다고 지레짐작하기 쉽다. 하지만 이런 기능으로 끝나지 않는다. 거의 모든 응용에서 특정 페이지 엘리먼트를 가리거나 다른 페이지 엘리먼트 상태에 맞춰 끄고 켤 필요가 있다. 이런 변화 유형이 RIA에 중요한 이유는 페이지를 한 번만 읽으면서 모든 페이지 엘리먼트를 가져온 다음에 특정 엘리먼트를 표시하고 가리는 방식으로 필요한 정보만 보여주기 때문이다. 페이지를 다시 읽는 대안은 좋은 해법이 아니다. div를 감추고 보여주는 두 가지 선택이 가능한 콤보 박스를 생각해보자. 명백히 콤보 박스가 바뀔 때마다 div를 감추고 보여주려고 페이지를 다시 읽어들이는 것보다 클라이언트 쪽 코드에서 단순히 div를 감추고 보여주는 방식이 훨씬 더 쉽고 효율적이다. 단순히 감추고 보여주느냐 페이드 인/아웃 효과를 주느냐는 설계자 마음이다.

위에서 언급한 바와 같이 가장 기초적인 효과는 show()hide() 함수다. 두 함수는 아주 직관적이며, 척 보면 알겠지만 페이지에 있는 특정 엘리먼트를 보여주고 감춘다.


Listing 1. show()와 hide() 함수
				
// 페이지에 나오는 모든 <p>를 보여준다.
$("p").show();

// 페이지에 나오는 모든 <p>를 감춘다.
$("p").hide();

// 페이지에 나오는 모든 <p:odd>를 감춘다.
$("p:odd").hide();

이런 기본적인 기능 이외에, show()hide() 함수는 보여주고 감추는 동작 방식을 좀 더 세부적으로 제어하는 기능도 제공한다. 문서에 따르면 "우아한" 보여주기/감추기 기능은 show()를 페이드 인과 슬라이딩 아웃 조합으로 해석한다.

몇 가지 예제를 살펴보기 앞서, 잠시 한 걸음 물러서서 Effects 함수에 인수를 전달하는 방법을 살펴보자. (일반적인 show()hide() 함수는 예외지만) 함수마다 효과를 완료하고 나서 부르는 함수와 얼마나 빠르거나 느리게 효과를 보여줄지 제어하는 속력을 전달할 수 있다. 속력 인수로 "slow", "fast", "normal"이라는 문자열 중 하나를 지정한다. 추가로 애니메이션 주기를 정확하게 제어할 필요가 있다면 인수로 밀리 초 단위의 숫자를 넘긴다. Effects 함수로 넘기는 두 번째 인수는 함수이며, 효과를 끝내고 나서 호출되는 함수다. 이렇게 하는 이유는 여러 효과를 좀 더 큰 효과 하나로 결합할 때 특정 효과가 끝나고 나서 다음 효과를 지시하는 안정적인 제어 방법을 제공하기 때문이다.


Listing 2. 복잡한 효과
				
// "picture"라는 ID를 지정한 img는 감춰진 상태로 시작한다.
// "showPicture" 버튼이 눌러졌을 때 "picture"라는 ID를 지정한 img를 보여주고
// 애니메이션을 한다. 따라서 잽싸게 페이드인과 슬라이드 아웃을 보여준 다음에
// 쇼가 끝나면 그림에 달린 캡션을 보여준다.
// 캡션은 항상 <img> 태그 오른쪽으로 펼쳐진다.

<input type="button" id="showPicture">

<img src="/pic.jpg" id="picture"><span>This is the picture's caption</span>

// document.ready() 함수 내부에 들어갈 jQuery 코드

$("#picture").hide().next().hide();
$("#showPicture").click(function(){
   $("#picture").show("fast", function(){
       $("#picture").next().show();
   });
});

// 실제 프로그램 코드보다 설명이 더 길어졌음에 주목하자!

Effects 모듈은 show()hide()와 아주 비슷해서 궁극적으로 똑같은 작업을 수행하는 다른 함수를 지원한다. 여기서는 아주 구체적인 동작을 수행하게 만드는 함수 군을 소개하겠다. slideDown()slideUp() 함수는 페이지 엘리먼트를 보여주고 감추는 함수다. 하지만 슬라이딩 다운/업으로 엘리먼트에 애니메이션 효과를 준다(작명에 아주 머리가 파았을 테다!). 조금 전에 설명한 개선된 hide()show() 함수처럼, 슬라이드 속력과 작업이 끝나면 호출될 함수를 제어할 수 있다. 한걸음 더 나가서 여기에는 페이지 엘리먼트를 보여주고/감추기 위한 다른 옵션도 있다. fadeIn()fadeOut() 함수는 이름이 의미하듯이 페이지 엘리먼트를 투명해질 때까지 페이드 효과를 줘서 최종적으로 사라지게 만든다. 이 옵션에도 속력과 작업이 끝나면 호출될 함수를 지정할 수 있다.

페이지 엘리먼트를 완전히 감추거나 보여주지 않는 흥미로운 함수가 하나 더 있다. fadeTo()라는 함수는 페이지 엘리먼트를 일부 투명하게 만든다. RIA에서 이런 기능이 아주 중요한 이유는 투명도는 특정 엘리먼트를 페이지에서 강조하는 훌륭한 수단이며, 페이지에서 비활성 영역을 보여주는 데 사용할 수 있기 때문이다. 예를 들어, 페이지에 여러 탭이 있는 상황에서 다른 탭이 선택하지 못한다는 사실을 강조하려고 나머지 탭에 투명도를 적용할 수 있다. 아니면 페이지 폼에서, 현재 초점이 어떤 Form 엘리먼트에 맞춰져 있는지 사용자에게 알려주고 싶을 때도 초점이 없는 모든 엘리먼트에 투명도를 가하면 구분이 가능하다. 또한 투명도 자체 효과만 해도 정말 멋지다. 뭔가를 디자인할 때 "애플이 하면 진짜 멋지다"라는 일반적인 후광 효과를 따르면 된다.


Listing 3. 멋진 효과를 추가하기 위해 fadeTo() 활용하기
				
// 페이지에 있는 모든 form 엘리먼트에 60%라는 투명도를 준다.
// 현재 초점이 있는 엘리먼트는 투명도 효과에서 제외한다.
// 애플처럼 보이지 않는가?

$(":input").fadeTo("fast", .60);
$(":input").focus(function(){
    $(this).fadeTo("fast", 1);
});
$(":input").blur(function(){
    $(this).fadeTo("fast, .60);
    });

Effects 모듈에서 소개하고픈 마지막 함수는 가장 멋지지만 가장 실수도 저지르기 쉬운 함수다. 이는 전용 애니메이션 메서드로 애니메이션에 필요한 모든 매개변수를 지정하면 나머지는 jQuery가 알아서 처리한다. 매개변수 배열에 최종값으로 넘기면 jQuery는 배열에 정의된 값을 판단해 역시 매개변수로 넘긴 속력을 적용해서 마지막 값에 이를 때까지 페이지 엘리먼트를 부드럽게 움직여준다. Listing 4는 전용 애니메이션 메서드 예를 보여준다. 말하지 않아도 알겠지만 이 함수 응용 분야는 제한이 없으므로, 독자적인 전용 애니메이션이 필요하다고 느낄 때 유용하게 써먹기 바란다.


Listing 4. 전용 애니메이션 메서드
				
// 버튼을 클릭하면, "movingDiv"라는 ID가 붙은 div에 전용 애니메이션 효과를 적용한다.
$("#myButton").click(function(){
   $("#movingDiv").animate({
      // "movingDiv"에 속한 width, opacity, fontSize를 늘리며, 5초 동안 지속한다.
      width: 700;
      opacity: 0.5;
      fontSize: "18px";
   }, 5000);
   });

Ajax

최근에 "Ajax를 사용합니까?"라는 유행어가 모든 웹 페이지에 등장하고 있지만, 모든 사람이 Ajax가 진짜로 무엇을 의미하는지 아는 건 아니다. "Ajax"를 구글에서 검색해 보면 (다른 검색 결과와 마찬가지로) 수백만 건에 이르는 결과가 나타나지만 Ajax 용어가 품고 있는 사상이 무엇인지를 혼동하고 있다는 증거처럼 보인다. Ajax는 몇몇 페이지에서 보여주는 진짜 멋진 애니메이션도 아니며 진짜 멋진 그림자가 아래에 깔린 팝업 창도 아니다. 단지 Ajax가 멋지기 때문에 웹 페이지에서 보여주는 모든 흥미로운 효과를 Ajax라고 부르지는 않는다. Ajax의 핵심은 간단하게 말해 클라이언트 쪽 웹 페이지가 페이지를 다시 읽어들일 필요 없이 서버와 정보를 주고받는 수단일 따름이다. Ajax가 페이지에서 화끈한 효과를 주지는 못하지만, 웹 응용이 데스크톱 응용을 흉내내기 위한 수단을 제공한다. 따라서 Ajax를 둘러싼 소문은 근거가 있다. Ajax를 광범위하게 사용하는 관례는 오늘날 볼 수 있는 RIA 부문의 급격한 성장을 견인하고 있다.

jQuery는 Ajax를 엄청나게 쉽게 만들어준다! 과장해 추켜세울 의도는 없다. 자바스크립트 라이브러리의 도움 없이 Ajax로 작업한다면 XMLHttpRequests를 사용해야 하는데, 마이크로소프트(Microsoft®)와 파이어폭스가 사용하는 XMLHttpRequests 사이에 벌어진 차이점을 인지하고 반환 코드를 파싱하고 그 밖에 온갖 작업을 몸소 진행해야 한다. jQuery는 Ajax를 함수 호출 한방에 끝내버린다. 농담이 아니다. 과거 100행에 이르는 코드는 현재 서너 줄이면 끝난다. 믿기 어려운 시간 절약이 아닌가? 개인적으로 jQuery를 알기 전에는 여기저기 Ajax 함수를 추가하는 데 상당한 작업이 필요한 듯이 보였다. jQuery를 사용하면 Ajax가 너무나도 단순한 작업으로 변하기에 Ajax가 제공하는 모든 기능을 십분 활용하도록 응용 프로그램을 수정해왔다. 일반 함수 호출처럼 단순하다면 사용하지 못할 이유가 무엇이랴?

독자적인 Ajax 코드를 만드는 데 가장 널리 사용하는 함수인 post()get() 메서드에 초점을 맞추자. 두 함수는 현재 이 기사를 읽고 있는 시점에서 일반적인 jQuery 함수와 상당히 비슷하게 동작한다. URL과 넘길 매개변수를 명세하고 Ajax 메서드를 종료할 때 수행하는 함수를 명세하면 된다. 두 함수를 설정하는 방식 때문에 jQuery에서 다른 함수 호출과 정확하게 일치하는 방식으로 Ajax 메서드를 호출할 수 있게 되었다. Listing 5를 살펴보자.


Listing 5. Ajax post()와 get() 메서드
				
// 이 코드는 myTest.php라는 php 파일에 들어간다.
// Ajax 예제를 설명하다가 PHP를 다룬 이유가 무엇일까?
// 자바/JSP를 설명하자면 지면이 부족하다.
// 서블릿 코드도 보여줘야 하기 때문이다. 하지만 PHP를 사용하면 이런 번거로움이 없다.
// 물론 두 함수는 PHP와 자바/JSP에서 제대로 동작한다.
<?php
     echo "This is my return String";
?>

// jQuery에서 Ajax를 호출하는 방법이 얼마나 간단한지를 보여준다.
// post 함수
$.post("myTest.php", {}, function(data){
   $("p").text(data);
});

// get 함수
$.get("myTest.php", {}, function(data){
   $("p").text(data);
   });

두 예제를 보면 알겠지만, 해당 함수는 다른 jQuery 함수와 거의 흡사하며, 자바스크립트 라이브러리 없이 Ajax 프로그램을 작성하는 경우와 비교해 훨씬 더 사용하기 쉽다. Ajax 호출 함수를 확장하기 위해 사용 가능한 몇 가지 인수가 있다. 첫 번째 인수는 두말할 필요없이 호출할 URL이 되어야 한다. PHP 파일, JSP 파일, 서블릿이 될 수 있으며, 실제로 요청을 처리할 수만 있다면 뭐든 가능하다. (나중에 예제 응용을 보면 알겠지만) 요청에 반드시 반응할 필요도 없다. 두 번째 인수는 옵션으로 post/get으로 넘길 자료를 담는다. 이 인수는 배열 형태다. 일반적으로 페이지에서 사용자 ID 등 Form 엘리먼트에 들어있는 정보를 넘길 때 사용한다. 서버 쪽 파일에서 요청을 처리하는 데 필요한 모든 내용을 담고 있다. 세 번째 인수는 역시 옵션이며 Ajax 함수가 성공적으로 끝나고 나서 호출할 함수다. 이 함수는 일반적으로 서버에서 전달하는 정보 결과를 처리하는 코드를 포함한다. Listing 6은 네 번째 인수 설명에 앞서 첫 세 인수를 활용하는 예제를 보여준다.


Listing 6. 추가 인수를 받아들이는 post 메서드
				
// username과 password 입력 필드를 페이지에 추가한다.
<input type=text id="username">
<input type=password id="pass">

// 서버 기반 PHP 파일을 호출한다. 서버쪽으로 전달한 정보를 이 파일 내부에서 처리한다.
$.post("myFormProcessor.php", {username: $("#username").val(), 
                               password: $("#pass").val()});

// 거꾸로, 이 PHP 파일은 받은 결과를 처리할 함수에게 정보를 반환할 수 있다.
$.post("myFormProcessor.php", {username: $("#username").val(), 
                               password: $("#pass").val()},
       function(data){
           // data 변수는 서버에서 반환된 텍스트를 포함한다.
           // 미리 설정할 내용은 없으며, jQuery가 알아서 대신 처리해준다.
           if (data != "ERROR")
              $("#responseDiv").text(data);
       }
       );

지금까지 jQuery로 Ajax를 다루는 방법은 아주 직관적이고 쉽다는 사실을 확인했다. 하지만 단순히 텍스트 문자열이 아니라 서버에서 좀 더 복잡한 정보를 다루기 시작하면 일이 꼬이기 시작한다. 더 많은 Ajax 호출이 걸려있는 좀 더 복잡한 웹 페이지에서 반환 자료는 XML 형태도 가능하다. 반환 자료는 또한 JSON 객체 형태가 될 수도 있다(JSON은 기본적으로 자바스크립트 코드에서 사용 가능한 객체를 정의하는 프로토콜이다). jQuery는 네 번째 옵션 인수로 서버에서 기대하는 반환 값 유형을 미리 정의하는 get/post 메서드에 넘기도록 허용한다. XML 문자열을 위해 "xml"이라는 문자열을 넘기고, HTML 문자열(또는 평문)을 위해 "html"이라는 문자열을 넘기고, 자바스크립트 코드를 위해 "script"라는 문자열을 넘기고, JSON 객체를 위해 "json"이라는 문자열을 넘긴다. 따라서 예를 들어, 반환 객체를 "json" 유형으로 지정하면 jQuery는 자동으로 서버에서 오는 반응 문자열을 JSON 객체로 바꿔 즉시 참조가 가능하게 만든다.


Listing 7. Ajax에서 반환 유형 명세하기
				
// 반환 객체를 JSON 객체 유형으로 정의하고, 객체 형 변환이나 평가 과정을 거치지
// 않고서 내부 필드를 참조하도록 반환 객체를 JSON 객체로 처리한다.

$.post("myFormProcessor.php", {username: $("#username").val(), 
                               password: $("#pass").val()},
       function(data){
          // jQuery는 이미 결과 자료를 JSON 객체로 변환했기에, 
          // 즉시 내부 필드를 참조할 수 있다.
          // 좀 더 깔끔한 코드를 제공하며, 향후 변경에 대응이 가능하다.
          // XML 결과를 직접 처리하는 경우와 비교하면 작업이 훨씬 쉬워진다.
          $("#username").text(data.username);
          $("#address").text(data.address);
          $("#phone").text(data.phone);
       }, 
       "json"  // 여기서 반환 유형이 JSON이라고 명세한다.
       ); 

설명에 시간을 들일 만한 또 다른 Ajax 함수는 load()이며, 사용자가 특정 페이지를 읽어서 결과로 HTML을 얻도록 만들어준다. 설명만 보면 그다지 흥미를 못 느낄지도 모르겠다. 하지만 시작 시점에서 웹 페이지를 파싱하듯이 jQuery 코드를 사용해 반환된 정보를 파싱하는 능력이 생긴다. 이게 무슨 이야기일까? 웹 페이지를 읽은 다음에 jQuery로 파싱이 가능한 능력을 토대로 아주 효율적이고 프로그램 작성이 쉬운 웹 로봇을 직접 만들 수 있다. 특정 페이지에서 어떤 정보 유형도 수집할 수 있다. 예제를 한번 살펴보자.


Listing 8. load() 함수 예
				
// 야후 주식 시세를 호출하는 방법으로 아주 기본적인 주식 시세 시스템을 구축한 다음에
// 야후 주식 시세 페이지에서 정보를 긁어온다.
// 여기서는 IBM 주식 가격을 찾아 "stockPrice"로 ID를 설정한 텍스트 필드에서 보여준다.
// 주식 가격을 포함한 ID는 "yfs_190_ibm"이다.
$("#stockPrice").load("http://finance.yahoo.com/q?s=ibm #yfs_l90_ibm").text();

Ajax 모듈에서 소개할 마지막 두 함수는 Ajax 작업을 훌륭하게 보조해 주는 진짜 유틸리티 함수다. 이미 여러 차례 지적한 바와 같이 클라이언트와 서버 사이에서 일어나는 상호 작용 대다수는 폼과 폼이 포함하는 엘리먼트를 둘러싸고 일어난다. 이런 통신 유형이 아주 일반적이므로 jQuery에는 두 가지 유틸리티 함수가 있어서 HTTP 질의 문자열이거나 JSON 문자열 형태로 서버 쪽에 전달할 매개변수 생성을 도와준다. Ajax가 요구하는 조건에 맞춰 지원하는 유틸리티 함수를 골라 활용한다. 활용법이 아주 간단한 이유는 전체 폼을 캡슐화하므로 개발 도중에 자유롭게 엘리먼트를 추가, 삭제, 변경할 수 있기 때문이다. Listing 9는 이런 예제를 보여준다.


Listing 9. serialize()serializeArray() 함수
				
// serialize() 함수는 지정 엘리먼트에 들어있는 모든 폼 엘리먼트를 살핀 다음에
// 자동으로 엘리먼트의 모든 정보를 포함하는 <element name>=<element value>&
// 형태로 HTTP 문자열을 만든다.
// 예는 "firstname=Michael&lastname=Abernethy"와 같다.
// 이렇게 만든 문자열을 Ajax 호출로 정보를 전달할 URL 뒤에 덧붙인다.
$.post("myFormProcessor.php?" + $("#myForm").serialize());

// 또한 serializeArray() 함수로 비슷한 작업을 수행할 수도 있다.
// 폼을 JSON 형태로 변환한다.
$.post("myFormProcessor.php", {json: $("#myForm").serializeArray()});

여기서 배운 모든 내용을 하나로 합치기

모든 내용을 하나로 합쳐서 만든 데모 웹 응용인 웹 메일을 마지막으로 살펴보자. 이미 지난 연재물에서 충분히 익숙하게 살펴보았을 것이다. 정보 획득을 위해 클라이언트 쪽에서 서버 쪽으로 여러 Ajax 호출을 수행한다. 여기서는 메시지를 읽고 메시지를 지울 때 AJax를 활용한다. 그러고 나서 Effects를 활용해 사용자가 메시지를 지울 때 즉시 화면에서 메시지를 사라지게 만든다. 심지어 사용자가 페이지를 다시 읽지 않으며 Ajax 호출을 활용해 비동기식으로 실제 삭제가 일어나지만 이런 삭제 동작이 즉시 일어난다. 직접 만든 웹 응용에서 Ajax 호출이 얼마나 쉬운지를 살펴보고 데스크톱 응용을 진짜로 흉내내기 위해 Ajax를 활용하는 방법을 살펴보고, Effects를 활용해 응용 프로그램 사용성을 높이는 방법을 예제를 보면서 최종적으로 확인한다.


Listing 10. 예제 웹 응용: 메시지 삭제하기
				
// 먼저 메시지 삭제를 처리하는 방법을 살펴보자.

// 첫 단계는 실제로 메시지를 지울 버튼 생성이다.
<input type=button id="delete" value="Delete">

// 다음으로 테이블 각 행에 체크박스를 추가해 사용자가 삭제를 원하는 메시지를
// 선택하도록 만든다. 이런 체크박스를 나중에 활용할 텐데, 여기에 들어있는 정보는
// 아주 중요하다(예시라고 부른다).
// 각 체크박스 값이 message.id라는 사실에 주목하자.

<tr class="messageRow" id="<%=message.id %>">
<input type=checkbox name="delId" value="<%=message.id%>" class=selectable>

// 이제 HTML이 완료되었으므로 삭제를 수행하는 jQuery 코드를 살펴보자.

// 먼저, 삭제 버튼에 이벤트를 추가한다. 버튼을 누르면 체크된 메시지를 지우기 시작한다.

$("#delete").click(function() {
   deleteMessages();
});

// 마지막으로 deleteMessage() 함수를 정의하자. 오늘 배운 내용에서 가장
// 중요한 내용을 담고 있다.
// 모든 기사에서 다룬 내용을 완성하는 함수이므로, 동작 원리를 자세히 설명하겠다.
// 참고 1 - 아주 구체적인 검색 매개변수를 넘겨 체크된 체크박스를 하나씩
// 순회하며 "selectable" 클래스 멤버만 찾도록 만든다.
// 참고 2 - 체크박스 값이 포함된 테이블 행 ID와 동일하므로, Effects 모듈을 사용해
// 전체 테이블 행을 감출 수 있다. 체크박스 값을 전달하고 표 행을 다시 얻은 다음에 감춘다.
// 참고 3 - Ajax를 호출해 실제로 DB에서 메시지를 삭제한다. messageID를 서버에 전달해
// 삭제될 항목을 알도록 만든다. 체크박스 값에 포함된 정보를 Ajax 호출 과정에서 전달한다.
// 성공인지 아닌지 신경쓰지 않기 때문에 서버에서 돌아오는 대답을 무시한다.

function deleteMessages()
{
    $(".selectable:checked").each(function() {
        $("#"+$(this).val()).remove();
        $.post("<%=HtmlServlet.DELETE_MESSAGES%>.do", {delId: $(this).val()});
    });
    }

두 번째 예제로, 메시지를 읽는 방법을 살펴보자. jQuery에서 Ajax를 활용하는 예를 보여준다.


Listing 11. 예제 웹 응용: 메시지 읽기
				

// 지금까지 예제에서 코드 대부분을 살펴보았으므로, 코드에서 Ajax 부분만 초점을 맞춘다.
// 참고 1 - Ajax 호출을 하면서 인수 네 개를 정의해 넘긴다.
// 메시지를 읽으려면 서버에 두 변수를 넘겨야 한다.
// 첫 번째는 메시지 ID로 읽기를 원하는 메시지가 무엇인지 알아야 하기 때문이다.
// 두 번째는 현재 뷰로 .. 어떤 목적으로 사용했는지 기억나지 않는다.
// (그다지 중요하지 않는 듯이 보인다)
// 참고 2 - Ajax 함수로 넘기는 네 번째 인수는 "json"이다.
// Ajax 호출로 JSON 객체를 반환하라는 표식이다. jQuery는 결과로 반환되는
// 문자열을 JSON 객체로 자동으로 변환한다.
// 참고 3 - eval() 함수를 사용하지 않고 JSON 객체를 직접 다루고 있다는 점에 주목하자.
// jQuery가 객체를 만들었기 때문이다. 따라서 필드를 직접 참조할 수 있다.
$(".messageRow").dblclick(function() {
    if ($(this).hasClass("mail_unread"))
    {
        $(this).removeClass("mail_unread");
    }
    $.post("<%=HtmlServlet.READ_MESSAGE%>.do", {messageId: $(this).attr("id"),
                                                     view: "<%=view %>"}, 
      function(data){
        if (data != "ERROR")
        {
             // JSON 객체를 활용한다.
             $("#subject").val(data.subject);
             $("#message").val(data.message);
             $("#from").val(data.from);
         }
      }, "json");
    $.blockUI(readMess, {width:'540px', height:'300px'});
    });

결론

jQuery와 같은 자바스크립트 라이브러리는 데스크톱에서 브라우저로 응용 프로그램을 이식함에 따라 점점 더 중요해진다. 이런 응용은 점점 더 복잡해지므로, 웹 응용 프로젝트에서 jQuery와 같은 튼튼한 교차 브라우저 해법을 필수로 요구한다. jQuery는 다른 자바스크립트 라이브러리와 격차를 벌이기 시작했으며, 필요한 모든 작업을 수행하는 능력과 함께 손쉬운 개발 특성 때문에 많은 개발자가 jQuery를 핵심 라이브러리로 선택하고 있다.

연재물 세 번째 기사에서, 응용에 풍부함을 더해 데스크톱 응용과 웹 응용 사이에 경계를 허무는 두 가지 모듈을 익혔다. 이번 기사에서 가장 강력하게 추가한 내용은 Ajax 모듈로, 다른 jQuery 메서드 호출처럼 간단하고 직관적인 인터페이스를 제공함으로써 Ajax를 아주 쉽게 활용하도록 만든다. 페이지를 다시 읽느라 지연되는 짜증을 겪지 않고서 응용 프로그램 반응 속력을 높이는 훌륭한 도구로 몇 가지 예제를 곁들여 Ajax의 위력도 살펴보았다. Effects 패키지에 대한 내용도 빠지지 않았다. 애니메이션과 페이지 엘리먼트 감추기/보여주기 기능을 적절하게 사용한다면 좋은 UI 디자인이라는 강력한 지원군을 얻게 된다. Ajax와 Effect를 결합해 효율적으로 활용하면 웹 사이트에 동적인 능력을 상당히 강화할 수 있다.

마지막으로 웹 응용 예제를 다시 한번 살펴보았고, AJax 모듈을 추가해 페이지를 다시 읽어들이지 않고도 메시지를 읽고 삭제하는 방법을 익혔다. 그러고 나서 Ajax와 Effect 조합으로 페이지를 다시 읽어들이지 않고도 사용자 페이지와 DB 웹 응용에서 메시지를 삭제하는 방법을 익혔다. 사용자에게 메시지 삭제는 투명한 과정이며, 미리 정해진 방식에 맞춰 프로그램 상에서 동작한다.

이 기사는 모든 jQuery 배포판에 따라오는 핵심 라이브러리에 대한 소개 내용으로 마무리를 한다. 연재물에서 jQuery에 포함된 모든 모듈을 살펴보았으며, jQuery로 작업하는 과정이 쉽고 직관적이라는 사실을 보여줬다. 또한 어떤 웹 응용을 만들거나 jQuery는 RIA 유형에 무관하게 제 자리를 잡고 있다는 사실을 확인했다. 자바스크립트가 요구하는 수준에 맞춰 튼튼한 토대를 제공하기 때문이다. 연재물은 직접 코드를 작성하는 과정에서 jQuery를 아주 자연스럽게 활용하는 수준에 이르도록 독자들을 이끌었다. 첫 번째 기사는 jQuery 동작 방식, 페이지 엘리먼트 탐색을 위한 활용 방법, 엘리먼트를 순회하는 방법, Array 객체와 같은 방식으로 접근하는 방법을 설명했고, 두 번째 기사는 풍부함을 제공하는 토대로 세 가지 모듈을 소개했다. 마지막으로 세 번째 기사는 완벽하고 복잡한 웹 응용을 만들기 위한 프레임워크를 위한 마지막 퍼즐 조각을 보여줬다.





위로


다운로드 하십시오

설명 이름 크기 다운로드 방식
예제 애플리케이션을 담은 Zip 파일 jquery.zip 69KB HTTP
다운로드 방식에 대한 정보




'DHTML > Javascript' 카테고리의 다른 글

http://visualjquery.com/  (0) 2009.08.05
[펌]jQuery로 Ajax 개발을 단순화 하기  (0) 2009.07.30
ExtJS --> XmlTreeLoader Error....  (154) 2009.06.26
[그래프 툴] jquery flot  (0) 2009.06.18
[펌] 부모창과 닫히는 팝업창  (0) 2009.04.28
Posted by tornado
|

Extjs 2.2.1 을 다운로드 받아서 트리메뉴와 layout 을 이용하려고 했다.

TreeMenu 를 구성하는 데이터는 XML 을 이용함.

그러나!!!! 의도된 동작이 일어나지 않음.

FireBug 를 동원하여 에러분석 돌입.

FireBug 에서는 405 Method Not Allowed  에러 메시지 출력.

그래서... Xml을 읽어오는 TreeLoader 에 옵션으로 아래와 같이 설정.

requestMethod:'GET'

동작 잘 한다...


아래는 ExtJS 에서 제공하는 XmlTreeLoader 샘플 Javascript 파일이다.

붉은 글씨를 유의하여 보면 됨.

 
/*
 * Ext JS Library 2.2.1
 * Copyright(c) 2006-2009, Ext JS, LLC.
 * licensing@extjs.com
 *
 * http://extjs.com/license
 */


//
// Extend the XmlTreeLoader to set some custom TreeNode attributes specific to our application:
//
Ext.app.BookLoader = Ext.extend(Ext.ux.XmlTreeLoader, {
    processAttributes : function(attr){
        if(attr.first){ // is it an author node?
           
            // Set the node text that will show in the tree since our raw data does not include a text attribute:
            attr.text = attr.first + ' ' + attr.last;
           
            // Author icon, using the gender flag to choose a specific icon:
            attr.iconCls = 'author-' + attr.gender;
           
            // Override these values for our folder nodes because we are loading all data at once.  If we were
            // loading each node asynchronously (the default) we would not want to do this:
            attr.loaded = true;
            //attr.expanded = true;
        }
        else if(attr.title){ // is it a book node?
           
            // Set the node text that will show in the tree since our raw data does not include a text attribute:
            attr.text = attr.title + ' (' + attr.published + ')';
           
            // Book icon:
            attr.iconCls = 'book';
           
            // Tell the tree this is a leaf node.  This could also be passed as an attribute in the original XML,
            // but this example demonstrates that you can control this even when you cannot dictate the format of
            // the incoming source XML:
            attr.leaf = true;
        }
    }
});

Ext.onReady(function(){
 
    var detailsText = '<i>Select a book to see more information...</i>';
   
 var tpl = new Ext.Template(
        '<h2 class="title">{title}</h2>',
        '<p><b>Published</b>: {published}</p>',
        '<p><b>Synopsis</b>: {innerText}</p>',
        '<p><a href="{url}" target="_blank">Purchase from Amazon</a></p>'
 );
    tpl.compile();
   
    new Ext.Panel({
        title: 'Reading List',
     renderTo: 'tree',
        layout: 'border',
     width: 500,
        height: 500,
        items: [{
            xtype: 'treepanel',
            id: 'tree-panel',
            region: 'center',
            margins: '2 2 0 2',
            autoScroll: true,
         rootVisible: false,
         root: new Ext.tree.AsyncTreeNode(),
           
            // Our custom TreeLoader:
         loader: new Ext.app.BookLoader({
             dataUrl:'xml-tree-data.xml'
             , requestMethod: 'GET'
         }),
           
         listeners: {
             'render': function(tp){
                    tp.getSelectionModel().on('selectionchange', function(tree, node){
                        var el = Ext.getCmp('details-panel').body;
                     if(node.leaf){
                         tpl.overwrite(el, node.attributes);
                     }else{
                            el.update(detailsText);
                        }
                    })
             }
         }
        },{
            region: 'south',
            title: 'Book Details',
            id: 'details-panel',
            autoScroll: true,
            collapsible: true,
            split: true,
            margins: '0 2 2 2',
            cmargins: '2 2 2 2',
            height: 220,
            html: detailsText
        }]
    });
});




Posted by tornado
|
출처 : http://code.google.com/p/flot/


Flot is a pure Javascript plotting library for jQuery. It produces graphical plots of arbitrary datasets on-the-fly client-side.

The focus is on simple usage (all settings are optional), attractive looks and interactive features like zooming and mouse tracking.

The plugin is known to work with Internet Explorer 6/7/8, Firefox 2.x+, Safari 3.0+, Opera 9.5+ and Konqueror 4.x+. If you find a problem, please report it. Drawing is done with the canvas tag introduced by Safari and now available on all major browsers, except Internet Explorer where the excanvas Javascript emulation helper is used.

Examples

Take a look at the examples to see how it works, or look at FlotUsage to see some real projects using Flot.

Documentation

Besides the examples, there's a README, FAQ and the API documentation, all for the development version. The NEWS will tell you the changes.

You could also take a look at the TODO, although most of the suggestions are in the bug tracker.

If you need more help, you can ask on the mailing list. You can probably save yourself some time skimming the FAQ first.

Who's behind this?

The development so far has mostly been done by Ole Laursen, sponsored by IOLA, a small Danish web-development house focusing on Django and jQuery. If you need commercial support, you're welcome to contact us.

Posted by tornado
|

Internet Explorer에는 showModelessDialog 라는 메소드가 있어서 팝업이지만 상당히 빨리뜨고, 또한 부모창과 함께 닫히는 팝업창의 구현이 가능합니다.

자세한 것은 MSDN 참고하세요.


http://msdn.microsoft.com/library/default.asp?url=/workshop/author/dhtml/reference/methods/showmodaldialog.asp

 

또한 Mozilla 계열(Firefox, Netscape 등) 에서도 비슷하게 팝업창을 열 수 있습니다.
바로 window.open 을 할 때, modal=yes 라는 값을 추가하면 됩니다. 혹시 부모창이 닫힐 때 같이 닫히지 않는다면(테스트 결과 탭이 닫히는 것이 아닌 프로그램이 완전히 종료될때 닫힙니다), dependent=yes 라는 값을 추가로 주시기 바랍니다.

원래는 showModalDialog 와 같은 효과를 바라고 검색하다가 찾은건데 정작 제가 원했던 것은 아직 지원안되는 모양입니다. ^^a

위의 내용을 바탕으로 대충 구현한 함수는 다음과 같습니다.
차이점을 잘 모르겠다는 분들은 주소표시줄을 눈여겨 보세요. (^_^)

 

function modelessWindow(url, name, width, height){
  if  (window.showModelessDialog) {
    
window.showModelessDialog(url, name,'dialogWidth:'+width+'px;dialogHeight:'+height+'px');
  }
  else
  {
     var win = window.open(url, name, 'height='+height+',width='+width+',toolbar=no,directories=no,status=no,linemenubar=no,scrollbars=no,resizable=no,modal=yes,dependent=yes');
   }
}

출처:http://mygony.com/archives/category/web/page/5/

'DHTML > Javascript' 카테고리의 다른 글

ExtJS --> XmlTreeLoader Error....  (154) 2009.06.26
[그래프 툴] jquery flot  (0) 2009.06.18
NS/FireFox equiv of event.srcElement  (0) 2008.12.07
[링크] 스크립트 주석 표준  (0) 2008.07.29
마우스 우클릭 금지  (0) 2008.03.08
Posted by tornado
|
xxxObj.onclick = function (e) {
 if (window.event) e = window.event; 
var srcEl = e.srcElement? e.srcElement : e.target;
// srcEl now can be used x-browser.
// (rest of the script here)
}

-----------------------------------------------------------------------
ex) 쇼핑몰 : 판매업체 선택 --> 상품 목록 출력 --> 가격출력 순으로 작업되면
아래와 비슷한 함수들을 만들어 놓고 사용함

function printGoods(e){
if (window.event) e = window.event;
var srcEl = e.srcElement? e.srcElement : e.target;

if(!srcEl) return;

var vendorCode = srcEl.abbr;

if(!vendorCode) return;

var hidVendorCode = document.getElementById("hidVendorCode");
hidVendorCode.value = vendorCode;

var tmpArr = new Array();

for(var i = 0; i < goodsArr.length; i++){
if(goodsArr[i].VENDOR_CODE == vendorCode){
tmpArr.push(goodsArr[i]);
}
}

for(var i = 0; i < tmpArr.length; i++){
var id = "goodsTD_"+ (i + 1);
var goodsTD = document.getElementById(id);

if(goodsTD){
goodsTD.innerHTML = tmpArr[i].GOODS_NAME;
goodsTD.abbr = tmpArr[i].GOODS_CODE;
addEvent(id, "click", printPrice );
}
}
}



'DHTML > Javascript' 카테고리의 다른 글

[그래프 툴] jquery flot  (0) 2009.06.18
[펌] 부모창과 닫히는 팝업창  (0) 2009.04.28
[링크] 스크립트 주석 표준  (0) 2008.07.29
마우스 우클릭 금지  (0) 2008.03.08
TextArea 에 숫자만 입력하기  (0) 2007.11.14
Posted by tornado
|
http://www.scriptdoc.org/specification.htm

-----------------------------------------------------------------------------------

Home Page | Forums

Introduction

This reference page provides comprehensive documentation for all ScriptDoc tags, in alphabetical order.

Several tags have "synonyms" where you can use two differently named tags to document the same thing. You can use a synonym by using the exact same syntax as the original tag, but just substituting the tag name.

The section for each tag includes the following information:

  • Short description of the tag
  • Syntax
  • What the tag applies to
  • Longer explanation of the tag
* Example (Some tags have multiple examples)

Reference

The following tags are valid for code documentation:

@alias

ID for a class or function.

Applies to: Any

Syntax

@alias fooBar

Description

Use the @alias tag to ID a class or function if you have used a "shorthand" way to code the full name for that class or function.

Example

This example shows the @alias tag used to id a function called fooBar in the FOO.Lib namespace.

FOO.Lib.update(FOO.Lib, {
    
/**
 * Returns a function that will return a number one greater than the previous returned value, starting at n.
 * @alias fooBar
 * @alias FOO.Lib.fooBar
 * @param {Object} n	Number to start with. Default is 1.
 * @return {Function) Returns a function that will return a number one greater than the previous returned value.
 */
    fooBar: function (n/* = 1 */) {
        if (arguments.length === 0) {
            n = 1;
        }
        return function () {
            return n++;
        };
    },


@author

Author of a JavaScript file or function.

Applies to: Any

Syntax

@author Author-name [email]

Description

Use @author to credit the author of a JavaScript file or function.

Example

This example shows the @author tag used with the @fileoverview and @version tags to provide header information for a JavaScript file.

/** 
* @projectDescription 	Joe Smith's wonderful JavaScript library.
*
* @author	Joe Smith jsmith@company.com
* @version	0.1 
*/

@classDescription

Description of the class.

Applies to: Function

Syntax

@classDescription Description

Description

Use the @classDescription tag to give a short description of the class (if applicable).

Example

This example shows a sample documentation block for a basic Shape class.

/**
* Create a new instance of Shape.
*
* @classDescription	This class creates a new Shape.
* @return {Shape}	Returns a new Shape.
* @type {Object}
* @constructor	
*/
function Shape() {
}

@constructor

Shows that a function is a constructor for a class.

Applies to: Function

Syntax

@constructor

Description

Use the @constructor tag to signify that a function is a constructor if you are coding in an object-oriented programming style.

Example

This example shows a sample documentation block for a basic Shape class.

/**
* Create a new instance of Shape.
*
* @classDescription	This class creates a new Shape.
* @return {Object}	Returns a new Shape object.
* @constructor	
*/
function Shape() {
}

@deprecated

Signifies that a function or a property has been deprecated.

Applies to: Function or property.

Syntax

@deprecated

Description

Use the @deprecated tag to show that a function or a property has been deprecated and should not be used.

Example

This example shows a @deprecated tag added to a documentation block for a function.

/**
* This function gets a foo by name.
* @param {Object}	fooName	Name of the foo to retrieve.
* @return {Object}	Returns a new foo.
* @deprecated
*/

@exception

Specifies the type of exception thrown by a function.

Applies to: Function

Syntax

@exception {Exception} Exception-description

Description

Use the @exception tag to specify any exceptions thrown by a function. You can specify multiple exceptions in a documentation block.

Example

This example shows a function that throws two exceptions--a "MemoryException" and a "GeneralShapeException".

/**
* This function creates a new Shape object. 
*
* @exception	{MemoryException}	Throws a memory exception if out of memory. 
* @exception	{GeneralShapeException}	Throws a general shape exception if the object is not a shape.
* @return 	{Object}	Returns a new shape object.
*/

@id

Unique identifier for a function or property.

Applies to: All

Syntax

@id identifierName

Description

Use @id to link a function or property to its documentation in an external @sdoc file. Add the @id tag both inline right above a function and to the documentation block in the .sdoc file to create the link.

Example

This example shows an inline @id tag for the function foo.

/** @id */
function foo() {
   alert("Foo!");
}

@memberOf

Signifies that a function is a member of the specified class.

Applies to: Function, Property.

Syntax

@memberOf Class

Description

Use the @memberOf tag to signify that a function is a member of the specified class.

Example

This example shows that the getFoo function is a member of the fooBar class.

/**
* @memberOf fooBar
*/
function getFoo(){
}

@method

Signifies that a function is a method of a class, if applicable.

Applies to: Function

Syntax

@method

Description

Use the @method tag to signify a method of a class if you are coding in an object-oriented programming style.

Example

This example shows a @method tag.

/**
* @method
*/

@namespace

Creates the namespace prefix for a library file.

Applies to: File

Syntax

@namespace namespaceName

Description

Creates the link between the namespace of a library file and an external .sdoc file.

Example

This example shows how to use the @namespace tag to link the namespace of a library to an .sdoc file.

The excerpt below would go at both the top of the library file that contains the "ajax" namespace for the "snazzyLib" library and the corresponding "ajax.sdoc" file that contains the documentation for the "ajax" namespace in snazzyLib:

/**
 * @namespace snazzyLib.ajax
 */

@param

Use @param to tag each parameter for a function.

Applies to: Function

Syntax

@param {Type[, Type, ... ]} [Parameter |...] Parameter-Description

Description

Gives information about a parameter for a function. Specify the data type between the curly braces. If the parameter is optional, add '[]' around the parameter name.

Examples

Standard example

The following example shows a parameter for a function that takes a String named myDog.

/**
 * @param {String} myDog The name of the dog. 
 */

Optional parameter example

The following example shows an optional parameter that can be either a String or a Date.

/**
 * @param {String, Date} [myDate] Specifies the date, if applicable.
 */

Multiple objects example

The following example shows a parameter that can be one or more Strings.

/**
 * @param {String} ... Takes one or more dog parameters.
 */


@projectDescription

Gives a description of a JavaScript file.

Applies to: File.

Syntax

@projectDescription Description

Description

Use the @projectDescription tag as the first tag in the first documentation block for a JavaScript file. The @projectDescription tag signifies that the entire documentation block is part of a project description.

Example

This example shows the @projectDescription tag used with the @author and @version tags to provide header information for a JavaScript file.

/** 
 * @projectDescription	This library contains a lot of classes and functions.
 *
 * @author 	Joe Smith jsmith@company.com
 * @version 	0.1 
 */


@return

Specifies information about the return value(s) of a function.

Applies to: Function

Syntax

@return {Type [, Type, ...]} Returns-Description

Description

@return gives a description for the return value of a function.

Example

This example shows a return value for a function that returns a new foo object.

/** 
 * @return {Object} Returns a new foo object.	
 */

@sdoc

Defines the path to an external .sdoc file for a library file.

Applies to: File

Syntax

@sdoc filePath

Description

Associates an external @sdoc file with a JavaScript file. Use either a relative or absolute path.

Example

This example shows a documentation block that associates an "ajax.sdoc" file in the "scripts/snazzyLib" directory with the current JavaScript file:

/**
 * @sdoc scripts/snazzyLib/ajax.sdoc
 */

@see

Links to another related class or function.

Applies to: Any

Syntax

@see Class | #Function | Class#Function

Description

Use the @see tag to add a link to another class, a function within the current class, or a function in another class.

Examples

Function example

This example shows a link to a function named "foo" in the same class as the one being documented.

/**
 * @see #foo
 */

Class example

This example shows a link to a class named "fooBar".

/**
 * @see fooBar
 */

Function in another class example

This example shows a link to a function named "foo" in another class named "fooBar".

/**
 * @see fooBar#foo
 */

@since

Specifies since which version the library, function, or property became valid.

Applies to: File, Function, Property

Syntax

@since Version-number

Description

Specifies since which version the library, function, or property became valid.

Example

This example shows a @since tag, used in conjunction with @projectDescription, @author, and @version tags. A documentation block like this would go at the top of a JavaScript file.

/** 
 * @projectDescription	This library contains a lot of classes and functions.
 *
 * @author 	Joe Smith jsmith@company.com
 * @version 	1.1 
 * @since	1.0
 */

@type

Specifies what data type a property is.

Applies to Property

Syntax

@type {Type}

Description

Specifies what data type a property is.

Example

This example uses the @return tag with the @type tag to show the return type for a function that creates a new foo.

/**
 * This property describes what type of shape an object is.
 * @type {Object} This property describes what type of shape an object is.
 */

@version

Specifies the version number of the JavaScript file or class.

Applies to: Any

Syntax

@version Version-Number

Description

Specifies the version number of the JavaScript file or class.

Example

This example shows the @version tag used with the @projectDescription and @author tags to provide header information for a JavaScript file.

/** 
 * @projectDescription A description of the file ahead
 *
 * @author 	Joe Smith jsmith@company.com
 * @version 	0.1 
 */

'DHTML > Javascript' 카테고리의 다른 글

[펌] 부모창과 닫히는 팝업창  (0) 2009.04.28
NS/FireFox equiv of event.srcElement  (0) 2008.12.07
마우스 우클릭 금지  (0) 2008.03.08
TextArea 에 숫자만 입력하기  (0) 2007.11.14
JavaScript Throw Statement  (0) 2007.08.21
Posted by tornado
|
    <script type="text/javascript">
  <!--
  //Disable right click script
  //visit http://www.rainbow.arch.scriptmania.com/scripts/
  ///////////////////////////////////
  function clickIE() {if (document.all) {return false;}}
  function clickNS(e) {
   if (document.layers||(document.getElementById&&!document.all)) {
    if (e.which==2||e.which==3) {return false;}
   }
  }
  if (document.layers) {document.captureEvents(Event.MOUSEDOWN);document.onmousedown=clickNS;}
  else{document.onmouseup=clickNS;document.oncontextmenu=clickIE;}
  document.oncontextmenu=new Function("return false")
  // -->
 </script>

'DHTML > Javascript' 카테고리의 다른 글

NS/FireFox equiv of event.srcElement  (0) 2008.12.07
[링크] 스크립트 주석 표준  (0) 2008.07.29
TextArea 에 숫자만 입력하기  (0) 2007.11.14
JavaScript Throw Statement  (0) 2007.08.21
scriptaculous 응용한 accordion 메뉴...  (0) 2007.06.20
Posted by tornado
|

fn_ParseInt 손봐야함.. 소숫점 안됨.

-------------------------------------------------------------------------------
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE> New Document </TITLE>
  <META NAME="Generator" CONTENT="EditPlus">
  <META NAME="Author" CONTENT="">
  <META NAME="Keywords" CONTENT="">
  <META NAME="Description" CONTENT="">


  <script>
 var digitCheck = function(obj){
  if(!fn_ParseInt(obj.value)){
   alert("숫자만 입력하세요!!");
   var regEx = new RegExp('[^\\-\\+\\.\\d]','g');
   document.getElementById(obj.id).value = obj.value.replace(regEx, '');
  }
 }

 var fn_ParseInt = function(arg1){       
  if(fn_Trim(arg1).length == 0){
   return false;
  }

  var reg = /(^\d+$)|(^\d+\.\d+$)/;
      
  if(reg.test(arg1)){
   return true
  }else{
   return false;
  }
 }

 var fn_Trim = function(arg1) {
  return arg1.replace(/(^\s*)|(\s*$)/gi, "");
 }

  </script>
 </HEAD>

 <BODY>
  <form>
  <input type="text" id="digitTxt" onkeyup="digitCheck(this);" />
  <br />
  </form>

 </BODY>
</HTML>

Posted by tornado
|

펌질 했습니다. ^^

출처 : http://whiteship.tistory.com/986


JavaScript Throw Statement

AJAX/JavaScript : 2007/07/09 13:48



 

참조 : http://www.w3schools.com/js/js_throw.asp

throw문

throw문을 사용하여 예외를 생성할 수 이다. try-catch문과 함께 사용하여 프로그램의 흐름을 제어 할 수 있다.
예외는 문자열, 숫자, Boolean 또는 객체가 될 수 있다.

 문자열 예외를 발생시키는 예제
<html>
<body>
<script type="text/javascript">
var x=prompt("Enter a number between 0 and 10:","")
try
{
if(x>10)
throw "Err1"
else if(x<0)
throw "Err2"
}
catch(er)
{
if(er=="Err1")
alert("Error! The value is too high")
if(er == "Err2")
alert("Error! The value is too low")
}
</script>
</body>
</html>

특이하네요. 자바보다 훨씬 심플하군요.
Posted by tornado
|

아웃룩 메뉴 처럼 만들려고 하다가 혹시나 해서 구글 검색 해봤더니

벌써 만들어 놓으신 분이 계시군요.

출처 : http://www.lucasvd.nl/portfolio.php?id=24


Accordion for Script.aculo.us

Technieken: Javascript

This is a pretty advanced Accordion feature for Scriptaculous. It tries to be as much as the same as the Accordion feature from Mootools, but the original mootools version has still some more features, which I may add in the future.

How to use

Save the code below to accordion.js and put the file in your Scriptaculous directory.

Include the file in your webpage
Code:

<script type="text/javascript" src="js/accordion.js"></script>



Add the HTML for your accordion, for example:
Code:

<div id="accordion">
    <h3>Titlte 1</h3>
    <p>Text 1</p>
   
    <h3>Title 2</h3>
    <p>Text 2</p>
   
    <h3>Title 3</h3>
    <p>Text 3</p>    
</div>



And put just before the tag the Javascript:
Code:

<script type="text/javascript">
new Accordion("div#accordion h3", "div#accordion p");
</script>



Parameter explanation
Parameter 1
A CSS Selector which selects all titles

Parameter 2
A CSS Selector which selects all bodies[/b]

Parameter 3 Optional
A list of options, see below

Options

duration - Sets how long the effect should take

Example:
Code:

<script type="text/javascript">
new Accordion("div#accordion h3", "div#accordion p", {duration: 0.6});
</script>



_____________________________________________

default_open - The index, started at zero, of the body which should be open by default.

Example:
Code:

<script type="text/javascript">
new Accordion("div#accordion h3", "div#accordion p", {default_open: 2});
// Now the third body is open by default
</script>



______________________________________________________

event_trigger - On which event should the body be shown

Example:
Code:

<script type="text/javascript">
new Accordion("div#accordion h3", "div#accordion p", {event_trigger: 'over'});
</script>



Events

OnStart - called before a body is shown
OnFinish - called after a body is shown

Code

<?php // Just for highlighting, don't copy
/**
* Accordion Effect for Script.aculo.us
* Created by Lucas van Dijk
* http://www.lucasvd.nl
*
* Copyright 2007 by Lucas van Dijk
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*/

var Accordion = Class.create();

Accordion.prototype =
{
   
initialize: function(handles, bodys, options)
    {
       
this.options = this._set_options(options);        
       
this.headers = $$(handles);
       
this.bodys = $$(bodys);
        
        if(
this.bodys.length != this.headers.length)
        {
            throw
Error('Number of headers/bodys does not match!');
        }
        
        for(var
i = 0; i < this.headers.length; i++)
        {        
           
Event.observe(this.headers[i], this.options.event_trigger, this.show.bind(this, i));
            
           
this.bodys[i].style.display = "none";
        }
        
       
this.bodys[this.options.default_open].id = "visible";
        
       
this.show(this.options.default_open, true);
    },

   
show: function(index, force)
    {        
        if ((
index >= this.length) || (index < 0))
        {
            throw
Error('Index out of range');
        }
        
        if (
this.bodys[index].id == 'visible')
        {                                 
            if (
typeof force == "boolean")
            {                        
               
this.options.OnStart(index, this.bodys[index]);
                                
               
// Force display the visible object                
               
for(var i = 0; i < this.bodys.length; i++)
                {
                    if(
this.bodys[i].style.display != 'none' && i != index)
                    {
                        new
Effect.SlideUp(this.bodys[i]);
                    }
                }
                
                new
Effect.SlideDown(this.bodys[index]);
            }
        }
        else
        {        
           
this.options.OnStart(index, this.bodys[index]);
                        
           
// Normal change
           
new Effect.Parallel(
                [
                    new
Effect.Fade($('visible')),                
                    new
Effect.BlindUp($('visible')),
                    new
Effect.BlindDown(this.bodys[index]),
                    new
Effect.Appear(this.bodys[index])
                ], {
                   
duration: this.options.duration
               
}
            );
    
            $(
'visible').id = "";
           
this.bodys[index].id = "visible";
        }
        
       
this.options.OnFinish(index, this.bodys[index]);
    },
    
   
_default_options:
    {
       
duration: 0.3,        
       
default_open: 0,
       
event_trigger: 'click',
       
OnStart: function() { },
       
OnFinish: function() { }
    },
    
   
_set_options: function(options)
    {
        if(
typeof options != "undefined")
        {        
            var
result = [];
            for(
option in this._default_options)
            {
                if(
typeof options[option] == "undefined")
                {
                   
result[option] = this._default_options[option];
                }
                else
                {
                   
result[option] = options[option];
                }
            }
        
            return
result;
        }
        else
        {
            return
this._default_options;
        }
    }        
};

Effect.Accordion = Accordion;
Posted by tornado
|