http://jqueryui.com/demos/accordion/#default

http://docs.jquery.com/UI/Accordion#overview

http://jquery.bassistance.de/accordion/demo/

'JS > jquery' 카테고리의 다른 글

셀렉터  (0) 2012.01.17
폼관련  (0) 2012.01.17
기초함수  (0) 2012.01.17
jQuery의 기초  (0) 2012.01.17
유용한 JQUERY site  (0) 2012.01.17
JQUERY 플러그인  (0) 2012.01.17
Lazy Load Plugin for jQuery  (0) 2012.01.16
jQuery Fade In Scroll To Top Button With Smooth Scroll For Blogger  (0) 2012.01.16
Sticky Sidebar jQuery plugin  (0) 2012.01.16
jQuery를 이용해 스크롤바 따라다니는 레이어 만들기(IE6,IE7,IE8,크롬,사파리,파폭)  (0) 2012.01.16
by Anna 안나 2012. 1. 17. 19:14
1. 위치 기반 셀렉터

//[모든 짝수번째<p>엘리먼트를 선택한다.]
$("p:even");

//[모든 홀수 번째<p>엘리먼트를 선택한다.]
$("p:odd");

//[(첫|마지막)번째<p>엘리먼트를 선택한다.]
$("p:(first|last)");

//(첫|마지막)번째 자식 엘리먼트. 각 리스트의 (첫|마지막)번째의 아이템을 반환한다.
$("li:(first-child|last-child)")

//형제가 없는 모든 엘리먼트를 반환한다.
$("only-child")

//[모든 테이블에서 첫째행을 선택한다.] => n값은 1부터 시작
$("table tr:n-child(1)");

//[모든 테이블에서 (짝수 | 홀수)행을 선택한다.]
$("table tr:nth-child(even|odd)");

//[n번째로 일치하는 엘리먼트] => n값은 0부터 시작
$("eq(n)");

//[n번째(포함하지 않음) 이후로 일치하는 엘리먼트] => n값은 0부터 시작
$("gt(n)");

//[n번재(포함하지 않음) 이전의 일치하는 엘리먼트] => n값은 0부터 시작
$("lt(n)");


2.CSS 셀렉터

//[<body>의 바로 아래 자식인 <div> 엘리먼트를 선택한다.]
$("body > div");

//[확장자 pdf 파일의 링크를 선택한다.]
$("a[href$=pdf]");

//[http://로 시작하는 링크를 선택한다.]
$("a[href^=http://]");

//[<body>의 바로 아래 자식이면서 링크를 포함하는 <div>엘리먼트를 선택한다.]
$("body > div:has(a)");

//[속성값이 임의의 문자열을 포함하는 엘리먼트를 찾아오라]
$("a[href*=jquery.com]");

//[선택자 id someElement 에 html을 삽입한다.]
$("#someElement").html("엘리먼트에 텍스트를 추가한다.");

//[다수의 엘리먼트와 일치하는 셀렉터에 html 추가한다.]
$("div.fillMeIn").html("노드 그룹에 텍스트를 추가한다.");

//[모든 엘리먼트와 일치한다.]
$("*");

//[E 엘리먼트 형제로 바로 다음에 나오는 엘리먼트 F와일치]
$("E+F");

//[E 엘리먼트 형제로 다음에 나오는 엘리먼트 F와일치]
$("E~F");



3. 필터 셀렉터

//[애니메이션이 적용되고 있는 엘리먼트]
$(":animated");

//[모든 버튼을 선택한다.]
$(":button");

//[모든 체크박스를 선택한다.]
$(":checkbox");

//[선택된 체크박스나 라디오 버튼을 선택한다.]
$(":checked");

//[텍스트 foo를 포함 하는 엘리먼트만을 선택한다.]
$(":contains(foo)");

//[비활성된 모든 폼 엘리먼트를 선택한다.]
$(":disabled");

//[활성된 모든 폼 엘리먼트를 선택한다.]
$(":enabled");

//[모든 파일 엘리먼트를 선택한다.]
$(":file");

//[헤더 엘리먼트를 선택한다. <h1>~<h6>]
$(":header");

//[감춰진 엘리먼트를 선택한다.]
$(":hidden");

//[폼 이미지를 선택한다.]
$(":image");

//[폼 엘리먼트를 선택한다.(input,select,textarea,button)]
$(":input");

//[필터의 값을 반대로 설정한다.]
$(":not(filter)");

//[빈엘리먼트를 제외하고 텍스트도 포함해서 자식 엘리먼틀 가지는 부모 엘리먼트를 선택한다.]
$(":parent");

//[패스워드 엘리먼트를 선택한다.]
$(":password");

//[라디오 엘리먼트를 선택한다.]
$(":radio");

//[리셋버튼을 선택한다.]
$(":reset");

//[선택된 엘리먼트를 선택한다.]
$(":selected");

//[전송버튼을 선택한다.]
$(":submit");

//[텍스트 엘리먼트 선택한다.(input type=text)]
$(":text");

//[보이는 엘리먼트를 선택한다.]
$(":visible");
by Anna 안나 2012. 1. 17. 12:32
1.checkbox



-체크박스 체크 여부 : $('#checkboxid').is(":checked") //체크되었으면 true, 아니면 false를 반환
- 선택된 값 : $("input[name=objname]:checked").val()
- 선택 : $("input[name=objname]").filter("input[value=objvalue]").attr("checked", "checked");
- 해제 : $("input[name=objname]").filter("input[value=objvalue]").attr("checked", "");
- 선택된 갯수: $("input[name=objname]:checkbox:checked").length




2. select box


-value 값 가져오기 : var select_value = $("selectboxid > option:selected").val();
-값 설정 하기 : $("selectboxid > option[value=설정값]").attr("selected", "true");


3.팝업창에서 부모창에 값 셋팅하기.

$(opener.document).find('#sendMailYN').val( "1" );

팝업창에서 부모창의 input 라디오 타입을 검색하면서 값이 2일때 체크해준다.


4. radio 라디오버튼에서 선택된 값을 찾는 방법이다.. 첫번째 방법

     //라디오 버튼의이름이 "rdobtn"인것 중 선택되어진 항목의 값을 가져온다.
   -  var selectedValue = $('input:radio[name=rdobtn]:checked').val() ;

또는
   -  var selectedValue = $('input:radio[id=rdobtn]:checked').val() ;


두번째 방법

var selectedValue = "";
 var radios = $("input:radio");  //타입이 radio인 항목을 찾는다.
 for(var i = 0; i < radios.length;i++) //
 {
      if(radios[i].checked == true) //라디오 버튼중 선택되어진 항목의 값을 가져온다.
      {
          selectedValue = $(radios[i]).val() ;
      }
 }


by Anna 안나 2012. 1. 17. 12:32

1. jQuery함수 $(...) 

jQuery 함수 $(...)

jQuery(expression,context)

CSS 셀렉터를 받아 매치된 엘리먼트 집합의 jQuery 객체를 리턴한다.


예제1

div 엘리먼트 안의 모든 p 엘리먼트를 추출하여 테두리를 붙인다.

$("div > p").css("border", "1px solid gray");

예제2

document 첫번째 form 안에 있는 모든 input 태그 타입이 radio 인 것을 추출한다.

$("input:radio", document.forms[0]);

예제3

AJAX 응답으로부터 받은 XML에서 모든 div를 추출한다

$("div", xml.responseXML);

jQuery(html)

예제1

div를 비롯한 콘텐츠를 동적으로 생성하고 body에 추가한다.

$("<div><p>Hello</p></div>").appendTo("body")

예제2

input 요소를 type 요소없이 만들 수 없다. 

이것은 Microsoft의 read / write - once 규칙에 따른 것으로, 자세한 내용은 MSDN을 참조한다.

// IE에서 작동하지 않음

$("<input/>").attr("type", "checkbox");

// IE에서 작동

$("<input type='checkbox'/>");

jQuery(elements)

이 함수의 인수는 XML Documents와 Window 개체와 같이 DOM 엘리먼트가 아닌것도 받아들인다.

예제1

body의 배경색을 바꾼다 (css 메서드는 DOM Element에 없는 jQuery개체이다)

$(document.body).css( "background", "black" );

예제2

myForm 내의 모든 엘리먼트를 표시하지 않는다 ( 배열에는 모든 것을 한꺼번에 표시하지 않는 hide 함수는 존재하지 않는다)

$(myForm.elements).hide()

jQuery(callback)

$(document).ready()의 약어

DOM Document로드가 끝난 때 바인딩 해 놓은 함수가 실행된다. 

이 함수는 $ (document) ready ()와 같게 동작한다.

이 함수는 기술 적으로는 다른 $ () 함수와 마찬가지로 모두 가능하다, 쓰임새는 없다.

예제1

DOM 준비가 가능하면 작업을 수행한다.

$(function(){

  // Document is ready

});

예제2

$별칭을 사용하여 jQuery 코드가 안정적으로 동작하므로 전역 변수에 의지하지 않고 인수 $를 기술하도록한다. 

jQuery(function($) {

  // Your code using failsafe $ alias here...

});

 

2. jQuery Object 조작

each(callback)

일치한 전체의 Element에 대하여 함수를 실행한다.

이것은 일치하는 Element를 찾을 때 마다 1번씩 매번 함수가 실행되는 것을 의미한다.

함수에서 this 포인터는 각 Element를 의미한다.

예제1

div를 찾아서 color 프로퍼티를 변경한다.

  1. $(document.body).click(function () {
        $("div").each(function (i) {
  2.         if (this.style.color != "blue") {
  3.           this.style.color = "blue";
  4.         } else {
  5.           this.style.color = "";
  6.         }
  7.     });
  8. });

전체소스 : each_1.html

예제2

DOM Element 대신 jQuery  오브젝트를 사용하는 경우 $(this)를 기술

  1. $("span").click(function () {
  2.   $("li").each(function(){
  3.     $(this).toggleClass("example");
  4.   });
  5. });

전체소스: each_2.html

 

예제3

id가 stop인 div가 발견된 시점에 false를 반환하여 루프를 빠져나온다.

  1. $("button").click(function () {
  2.   $("div").each(function (index, domEle) {
  3.     // domEle == this
  4.     $(domEle).css("backgroundColor", "yellow"); 
  5.     if ($(this).is("#stop")) {
  6.       $("span").text("Stopped at div index #" + index);
  7.       return false;
  8.     }
  9.   });
  10. });

전체소스: each_3.html

eq(position)

0 부터 length-1 가운데 일치하는 위치에 있는 엘리먼트만 찾아온다.

예제1

P 태그 집합중 위치가 2번째인 Element색상을 바꾼다.

  1. $("p").eq(1).css("color","red")

전체소스:  eq_1.html

get()

jQuery 오브젝트가 가지고 있는 Element 전체를 배열 형태로 반환한다.

jQuery 객체가 아니라 DOM Element를 조작하는데 도움이된다.

예제1

div 요소를 get() 배열로 반환한다. 그리고 reverse() 내장함수를 이용하여 배열을 반전 표시한다.

 

  1. function disp(divs) {
  2.   var a = [];
  3.   for (var i = 0; i < divs.length; i++) {
  4.     a.push(divs[i].innerHTML);
  5.   }
  6.   $("span").text(a.join(" "));
  7. }
  8. disp( $("div").get().reverse() );

 

전체소스:  get_1.html

get(index)

DOM Element의 집합으로부터 인덱스를 지정해 하나의 Element를 참조한다.

이것에 의해 jQuery 오브젝트일 필요가 없는 케이스로 특정의 DOM Element 그 자체를 조작하는 것이 가능.

예제1

 

  1. $("*", document.body).click(function (e) {
  2.   e.stopPropagation();
  3.   var domEl = $(this).get(0);
  4.   $("span:first").text("Clicked on - " + domEl.tagName);
  5. });

 

전체소스:  get_index_1.html

 

index(subject)

jQuery 오브젝트 내에서 인수로 지정된 Element 인덱스를 리턴한다.

만약 jQuery 오브젝트 내에 존재하지 않으면 -1을 리턴한다.

예제1

페이지의 div의 인덱스를 리턴한다.

 

  1. $("div").click(function () {
  2.   // this is the dom element clicked
  3.   var index = $("div").index(this);
  4.   $("span").text("That was div index #" + index);
  5. });

 

전체소스:  index.html

 

length()

jQuery 오브젝트 Element 수를  유지한다. size 함수와 같은 값을 리턴

예제1

div를 카운팅하고 div를 추가한다.

 

  1. $(document.body).click(function () {
  2.   $(document.body).append($("<div>"));
  3.   var n = $("div").length;
  4.   $("span").text("There are " + n + " divs." +
  5.                  "Click to add more.");
  6. }).trigger('click'); // trigger the click to start

전체소스:  length.html

[출처] jQuery 함수 $(...)|작성자 하늘호수



http://blog.naver.com/ctlim2?Redirect=Log&logNo=50086952309
by Anna 안나 2012. 1. 17. 12:30
$(document).ready(function() {
(이곳에 시연하고자 하는 jquery 코드가 들어감.)
});
 
위의 코드가 jQuery를 시작하는 기본 코드가 됩니다. 
Javascript 에서의 window.onload = function() { } ;

부분과 비슷합니다만, 다른점은 자바스크립트의 onload가 모든 이미지들의 로딩이 마쳐야 시연되는 반면에, jQuery는 이미지가 로딩되지 않아도 시연이 됩니다.

 

페이지가 전부 다운로드 된다음에 실행

$(window).load(function() {
     해당 기능
});

HTML이 준비가 되면 실행

$(document).ready(function() {
     해당 기능
});
위 코드는  (document).ready를 생략해
$(function() {
     해당 기능
});
로도 사용가능합니다.

 

밑에 그림은 jQuery를 사용하기 위한 기초적인 형식입니다.


실제로 우리가 사용하는 코드는 윗그림의 빨강색 네모안에 들어가게 됩니다.
코드를 쓰시는 분에 따라서는 이렇게 눈에 잘보이게 정리하시지 않고 한줄에 몰아서 쓰시기도 합니다.
(잘 보시면 알겠지만 사실은 명령코드 하나입니다.)


빨강네모안에 들어갈 우리가 사용하는 코드는 밑에 그림과 같은 형식을 가집니다.

위의 코드에서 붉은 색 부분을 선택자(Selector) 라고 합니다. 즉, 구현할 대상에 되는 녀석을 선택하는 것이죠. 사용 방법은 $() 의 괄호안에 대상이 되는 녀석을 선택하는것입니다. jQuery가 좋은것이 선택자 개념이 CSS와 거의 흡사하기 때문에 쉽게 사용할수 있습니다.

'JS > jquery' 카테고리의 다른 글

Jquery Accordion 관련 링크  (0) 2012.01.17
셀렉터  (0) 2012.01.17
폼관련  (0) 2012.01.17
기초함수  (0) 2012.01.17
유용한 JQUERY site  (0) 2012.01.17
JQUERY 플러그인  (0) 2012.01.17
Lazy Load Plugin for jQuery  (0) 2012.01.16
jQuery Fade In Scroll To Top Button With Smooth Scroll For Blogger  (0) 2012.01.16
Sticky Sidebar jQuery plugin  (0) 2012.01.16
jQuery를 이용해 스크롤바 따라다니는 레이어 만들기(IE6,IE7,IE8,크롬,사파리,파폭)  (0) 2012.01.16
by Anna 안나 2012. 1. 17. 12:29

'JS > jquery' 카테고리의 다른 글

Jquery Accordion 관련 링크  (0) 2012.01.17
셀렉터  (0) 2012.01.17
폼관련  (0) 2012.01.17
기초함수  (0) 2012.01.17
jQuery의 기초  (0) 2012.01.17
JQUERY 플러그인  (0) 2012.01.17
Lazy Load Plugin for jQuery  (0) 2012.01.16
jQuery Fade In Scroll To Top Button With Smooth Scroll For Blogger  (0) 2012.01.16
Sticky Sidebar jQuery plugin  (0) 2012.01.16
jQuery를 이용해 스크롤바 따라다니는 레이어 만들기(IE6,IE7,IE8,크롬,사파리,파폭)  (0) 2012.01.16
by Anna 안나 2012. 1. 17. 12:28
http://www.trirand.com/blog/?page_id=6



그리드 (*) : 전체 페이징을 하지 않는 Ajax 게시판
http://www.reconstrukt.com/ingrid/example2.html





팬시박스 (**) : 이미지 팝업창에 모달효과 약간의 에니메이션이 들어감.
http://fancy.klade.lv/ (****)

예제 : http://fancy.klade.lv/example



jQuery Lightbox Plugin (balupton edition) (**) : 이미지 모달 팝업
http://www.balupton.com/sandbox/jquery_lightbox/



imagebox : 이미지 모달 팝업
http://www.intelliance.fr/jquery/imagebox/



이미지 회전 :  이미지의 회전이 가능하게 한다.

http://www.piksite.com/mRotate/mRotate.html



jQuery sliding gallery demo : 이미지 애니메이션 슬라이드
http://phplug.net/components/javascript/jquery-gallery.html



이미지 슬라이딩 : 좌 우로 움직임
http://www.maxb.net/scripts/ycodaslider-2.0/include/demo/#10



이미지 공간감 효과 (***)  :  여러 이미지를 레이어 겹쳐 놓음으로써 3D 효과를 준다.

http://webdev.stephband.info/parallax.html



디자이너를 위한 jquery (**) : 태그 조작과 에니메이션 효과와 관련된 사이트
http://www.webdesignerwall.com/demo/jquery/(****)


AutoScroll (*) : 컨 트롤 키 누른 채로 mouse 움직였을 때, 자동 스크롤이 가능하게끔
http://jdsharp.us/jQuery/plugins/AutoScroll/demo.php (****)


drag and drop (*) : 드래그 드랍 예제
http://host.sonspring.com/dragdrop/ (***)



JQuery 예제 모음 사이트 (*****)

http://www.ajaxrain.com/tag?tag=jquery


컬럭 Picker (****)  :  PhotoShop의 색 선택 기능이 가능.
http://www.intelliance.fr/jquery/color_picker/


jQuery MultiSelect (**) : custom 셀렉트 박스, 셀렉트 박스에 체크박스가 추가 되어 여러개를 선택 가능한 박스.
http://abeautifulsite.net/notebook_files/62/demo/jqueryMultiSelect.html


"jQuery checkbox v.1.0.0" demo (**)  : custom 디자인 체크박스
http://widowmaker.kiev.ua/checkbox/



jQuery Treeview Plugin Demo (**) : 트리 컨트롤러 1

http://jquery.bassistance.de/treeview/demo/



jQuery File Tree Demo (***) : JQuery 트리 컨트롤로 2
http://abeautifulsite.net/notebook_files/58/demo/



jQuery columnManager plugin (*) : 테이블의 컬럼을 추가 삭제등의 기능 제공
http://p.sohei.org/stuff/jquery/columnmanager/demo/demo.html


jQuery AIR (***) : ajax를 이용한 항공 좌석 예약.
http://www.digital-web.com/extras/jquery_crash_course/


Masked Input Plugin (**) : 입력상자에 exel과 같은 서식 적용.
http://digitalbush.com/projects/masked-input-plugin


Watermark Input Plugin (*): 입력상자에 워터마크 표시
http://digitalbush.com/projects/watermark-input-plugin



ClockPick (***): 입력상자에 시간을 선택해서 넣을 수 있다.
http://www.oakcitygraphics.com/jquery/clockpick/trunk/ClockPick.cfm


chart : JQuery를 이용한 차트
http://www.reach1to1.com/sandbox/jquery/jqchart/



달력
http://tedserbinski.com/jcalendar/index.html#demo



3D로테이션 : 글자들이 xy 좌표에서 3D효과로 회전함.
http://www.willjessup.com/sandbox/jquery/rotator/rotator.html


스크롤중 데이터가져오기 :
http://www.webresourcesdepot.com/dnspinger/
http://www.webresourcesdepot.com/load-content-while-scrolling-with-jquery/


Query Flash Plugin - Basic Example : flash 삽입 플러그인
http://jquery.lukelutman.com/plugins/flash/example-basic.html


jquery combobox demo : custom 콤보박스 ie 7.0으로 보면 깨져나온다.

http://jquery.sanchezsalvador.com/samples/example.htm


scrollable table : 테이블에 스크롤바가 붙어있다-_-;;
http://www.webtoolkit.info/demo/jquery/scrollable/demo.html



accordion-madness
http://www.learningjquery.com/2007/03/accordion-madness




jQuery Multimedia Portfolio
http://www.openstudio.fr/jquery/



체크박스 이동
http://sanisoft-demo.com/jquery/plugins/shiftcheckbox/demo.html


위지윅에디터
http://projects.bundleweb.com.ar/jWYSIWYG/


크랍
http://remysharp.com/2007/03/19/a-few-more-jquery-plugins-crop-labelover-and-pluck/#crop


슬라이딩 퍼즐
http://www.bennadel.com/blog/1009-jQuery-Demo-Creating-A-Sliding-Image-Puzzle-Plug-In.htm



날짜픽업
http://kelvinluck.com/assets/jquery/datePicker/v2/demo/


레이팅
http://php.scripts.psu.edu/rja171/widgets/rating.php


JQuery Curvy Corners Demo page
http://blue-anvil.com/jquerycurvycorners/test.html




http://www.mind-projects.it/blog/jqzoom_v10



LavaLamp for jQuery lovers!
http://gmarwaha.com/blog/?cat=8



컬러
http://www.jnathanson.com/blog/client/jquery/heatcolor/index.cfm#examples




비쥬얼 쿼리
http://visualjquery.com/1.1.2.html



jQuery "Highlight" Demo
http://www.keyframesandcode.com/resources/javascript/jQuery/demos/highlight-demo.html





Hot Key Testing
http://jshotkeys.googlepages.com/test-static.html






accordion menu
http://www.i-marco.nl/weblog/jquery-accordion-menu-redux/



jQuery easyThumb
http://www.hverven.net/div/easyThumb/


갤러리
http://www.flyerstop.ca/ui/apps/gallery_advanced/



thickbox
http://jquery.com/demo/thickbox/



마우스휠 플러그인
http://www.ogonek.net/mousewheel/jquery-demo.html
http://www.ogonek.net/mousewheel/demo.html

휴먼메세지
http://binarybonsai.com/misc/humanmsg/




jQuery - LinkedSelect
http://www.msxhost.com/jquery/linked-selects/json/



jQuery &#187; iFrame Sizing
http://host.sonspring.com/iframe/


jQuery for Designers - Ajax Form Validation Example
http://jqueryfordesigners.com/demo/ajax-validation.php


폰트크기 바꾸기
http://www.lllcolor.com/jQuery/demo/demo01b.html


dimension
http://brandonaaron.net/docs/dimensions/#code-samples


portlet 데모
http://www.rymix.co.uk/jquery/d15/sortables2.html


FX데모
http://magalies.net/downloads/Jquery/Interface%20examples/demos/ifx.html#pulsate-fx


오픈윈도우
http://magalies.net/downloads/Jquery/Interface%20examples/demos/windows.html


JQuery tricks: using Greybox + form plugin for a modal dialog box
http://corky.net/dotan/programming/jquery.dialog/dialog-demo.html



FaceBoox style autosuggest with jQuery
http://web2ajax.fr/examples/facebook_searchengine/


Auto-Growing Textarea Demo
http://www.aclevercookie.com/demos/autogrow_textarea.html


jQuery Helper for Komodo Media CSS Star Rater (Redux)
http://www.m3nt0r.de/devel/raterDemo/


에디터
http://avidansoft.com/dsrte/



jQuery Keyboard Navigation Plugin
http://amountaintop.com/project/keynav/



http://jqueryfordesigners.com/demo/tabs.html


jQuery AccessKey Demo
http://methvin.com/jquery/jq-access.html


Semi-transparent rollover effect using jQuery
http://coderseye.com/files/demos/pngrollover/index.html


Revealing Photo Slider
http://css-tricks.com/examples/RevealingPhotoSlider/


Simple jQuery form validation
http://www.willjessup.com/sandbox/jquery/form_validator/form_validate.html


after callback demo
http://jsdesigning.com/gal/gal.php?top=10&id_pic=9&id_album=2



갤러리
http://devkick.com/lab/galleria/demo_01.htm#img/ladybug.jpg



SWF Upload
http://www.alexandremagno.net/blog/wp-content/uploads/swfupload/index.htm

jQuery gradient - Visual Test
http://brandonaaron.net/jquery/plugins/gradient/test/


tEditable :: In place table editing for jQuery
http://joshhundley.com/teditable/index.html









sort
http://interface.eyecon.ro/demos/sort.html







































http://geeknation.blinklist.com/tag/jQuery/




http://www.nalanta.com/node/7
http://www.noupe.com/jquery/50-amazing-jquery-examples-part1.html
http://www.blinklist.com/mungkey/jquery/






http://geekswithblogs.net/AzamSharp/archive/2008/02/21/119882.aspx


http://www.learningjquery.com/2006/12/multiple-fancy-drop-caps

http://www.trirand.com/blog/?page_id=5



http://people.iola.dk/olau/flot/examples/selection.html(챠 트 선택)

http://www.mootools.net/dragdrop/

http://plugins.jquery.com/project/Plugins/category/21




http://mohamedshaiful.googlepages.com/add_remove_form.htm

http://www.chazzuka.com/Portofolio/


http://dev.jquery.com/view/tags/ui/1.5b2/demos/ui.sortable.html






http://hooney.net/code/2007/08/UnobtrusiveTabNav/tabNav03.html

http://jqueryfordesigners.com/coda-slider-effect/

http://benjaminsterling.com/jquery-jqgalview-photo-gallery/

http://www.mind-projects.it/blog/jqzoom_v10


http://www.reach1to1.com/sandbox/jquery/jqchart/

http://jquery.lukelutman.com/plugins/flash/

http://leandrovieira.com/projects/jquery/lightbox/

http://marcgrabanski.com/code/ui-datepicker/


http://www.noupe.com/ajax/37-more-shocking-jquery-plugins.html

http://www.webdesignerwall.com/demo/jquery/


http://www.gcmingati.net/wordpress/wp-content/lab/jquery/imagestrip/imageslide-plugin.html


http://cssglobe.com/post/1695/easiest-tooltip-and-image-preview-using-jquery


http://www.gcmingati.net/wordpress/wp-content/lab/jquery/imagestrip/imageslide-plugin.html


http://jquery.glyphix.com/


http://www.balupton.com/sandbox/jquery_lightbox/


챠트
http://www.filamentgroup.com/lab/creating_accessible_charts_using_canvas_and_jquery/


http://sorgalla.com/projects/jcarousel/

http://designreviver.com/tutorials/jquery-examples-horizontal-accordion

http://host.sonspring.com/portlets/

http://www.webdesignerwall.com/tutorials/jquery-tutorials-for-designers/

http://www.digital-web.com/extras/jquery_crash_course/



http://www.blinklist.com/codearachnid/jquery/

http://drupalmodules.com/module/image-enhanced-scaling

http://www.ajaxdaddy.com/store



http://www.ajaxrain.com/tag.php?tag=image&page=2(모음)
http://www.spicyexpress.net/general/jquerry-at-it-best- downloadable-jquerry-plugins-and-widgets-for-you-2/(예제모음)

http://mike.teczno.com/giant/pan/(pan)


출처 : 웃대가리블로그 - [추천]Jquery 링크 모음 - http://urin79.com/zb/utdae/783559
by 디케

http://defle.nayana.com/board/view.php?bbs_code=goodsite&ss[cat]=122&bd_num=1042
by Anna 안나 2012. 1. 17. 12:27
Lazy Load is a jQuery plugin written in JavaScript. It delays loading of images in long web pages. Images outside of viewport (visible part of web page) wont be loaded before user scrolls to them. This is opposite of image preloading.

Using Lazy Load on long web pages containing many large images makes the page load faster. Browser will be in ready state after loading visible images. In some cases it can also help to reduce server load.

Lazy Load is inspired by YUI ImageLoader Utility by Matt Mlinac.

For those in hurry there are several demo pages available: basic options, with fadein effect, noscript fallback, horizontal scrolling, horizontal scrolling inside container, vertical scrolling inside container, page with gazillion images and load images using timeout.

When checking the demos clear browser cache between each request. You can check what is actually loaded with developers console (Chrome and Safari), FireBug (Firefox) or HTTPHeaders (IE).

How to Use?

Lazy Load depends on jQuery. Include them both in end of your HTML code:

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

You must alter your HTML code. Put the place holder image into src attribute. Demo pages use 1×1 pixel grey gif. URL of the real image must be put into data-original attribute. It is good idea to give Lazy Loaded image a specific class. This way you can easily control which images plugin is binded to.

<img class="lazy" src="img/grey.gif" data-original="img/example.jpg"  width="640" heigh="480">

then in your code do:

$("img.lazy").lazyload();

This causes all images of class lazy to be lazy loaded. See the basic options demo.

Fallback for Non JavaScript Browsers

Practically everyone has JavaScript enabled. However there are cases when you want to show the real images even if request come from client which does not support JavaScript. Google crawlers are one good candidate. Google crawlers do not execute JavaScript but also seem to ignore noscript content. To degrade gracefully when JavaScript is not enabled you can include the real image tag inside <noscript> block.

<img class="lazy" src="img/grey.gif" data-original="img/example.jpg"  width="640" heigh="480">
<noscript><img src="img/example.jpg" width="640" heigh="480"></noscript>

To prevent both placeholder and the real image showing at the same time hide the place holder with css.

.lazy {
  display: none;
}

For JavaScript enabled browser you must enable displaying the placeholders when documents loads. This can be done at the same time when initializing the plugin.

$("img.lazy").show().lazyload();

All this is optional can should be done only if you want the plugin to degrade gracefully.

Setting Sensitivity

By default images are loaded when they appear on the screen. If you want images to load earlier you can set threshold parameter. Setting threshold to 200 causes image to load 200 pixels before it is visible.

$("img.lazy").lazyload({ threshold : 200 });

Event to Trigger Loading

Event can be any jQuery event such as click or mouseover. You can also use your own custom events such as sporty or foobar. Default is to wait until user scrolls down and image appears on the window. To prevent all images to load until their placeholder image is clicked you could do:

$("img.lazy").lazyload({ 
    event : "click"
});

Using Effects

By default plugin waits for image to fully load and calls show() to show it. You can use any effect you want. Following code uses fadeIn effect. Check how it works at effect demo page.

$("img.lazy").lazyload({ 
    effect : "fadeIn"
});

Images Inside Container

You can also use plugin for images inside scrolling container, such as div with scrollbar. Just pass the container as jQuery object. There is a demo for horizontal and vertical container.

#container {
    height: 600px;
    overflow: scroll;
}
$("img.lazy").lazyload({         
     container: $("#container")
});

When Images Are Not Sequential

After scrolling page Lazy Load loops though unloaded images. In loop it checks if image has become visible. By default loop is stopped when first image below the fold (not visible) is found. This is based on following assumption. Order of images on page is same as order of images in HTML code. With some layouts assumption this might be wrong. You can control loading behaviour with failure_limit option.

$("img.lazy").lazyload({ 
    failure_limit : 10
});

Setting failure_limit to 10 causes plugin to stop searching for images to load after finding 10 images below the fold. If you have a funky layout set this number to something high.

Delayed Loading of Images

Not exactly feature of Lazy Load but it is also possible to delay loading of images. Following code waits for page to finish loading (not only HTML but also any visible images). Five seconds after page is finished, below the fold images are loaded automatically. You can also check the delayed loading demo.

$(function() {          
    $("img:below-the-fold").lazyload({
        event : "sporty"
    });
});
$(window).bind("load", function() { 
    var timeout = setTimeout(function() {$("img.lazy").trigger("sporty")}, 5000);
}); 

Load Invisible Images

There are cases when you have invisible images. For example when using plugin in together with a large filterable list of items that can have their visibility state changed dynamically. To improve performance Lazy Load ignores hidden images by default. If you want to load hidden images set skip_invisible to false.

$("img.lazy").lazyload({ 
    skip_invisible : false
});

Download

Latest source or minified. Plugin has been tested with Safari 5.1, Firefox 3.6, Firefox 7.0, Firefox 8.0 on OSX and Firefox 3.0, Chrome 14 and IE 8 on Windows and Safari 5.1 on iOS 5 both iPhone and iPad.

When asking a question please include an URL to example page where the problem occurs. If you have longer code examples please use pastie.org





http://www.appelsiini.net/projects/lazyload
by Anna 안나 2012. 1. 16. 14:50
In October last year i wrote a post with a Floating back to top button.Since then i have wanted to cover a more up to date back to top modern button.The popular option when it comes to scroll top buttons is to use jQuery for two reasons.Firstly with jQuery you can have the button hidden until the page is scrolled, secondly when clicked the page scrolls smoothly to the top instead of the direct jump a regular link would have.So that's exactly what i have in this tutorial.We will add a button that will only be visible when the reader starts scrolling and then when they click it the page slowly scrolls up easing into position at the top.For the button itself we us a sprite to create a hover effect sprites also keep the page load time down.

I recently started a blog in which i want to list the Best Design and Blogging posts, codes, tutorials and resources.On that blog i have the back to top button we cover in this post so we will use that as the demo.When you land on the page start to scroll and you will see the button in the bottom right corner.

Design and Blog

Looks and Works great lets add it to your blog.Credits to Matt Verone, Wordpress users can use the plugin here.

Smooth Scroll jQuery Back To Top Button


Remember Always Back Up Your Template Before You Make Changes - How To Back Up A Blogger Template

Step 1. In Your Blogger Dashboard Click Design > Edit Html

Design Edit Html Blogger

Step 2. Find the following piece of code in your blogs Html : (Click Ctrl and F for a search bar to help find the code - How To Find Code In Blogger Template Template)

]]></b:skin>

Step 3. Copy and Paste the following code Directly Above / Before ]]></b:skin>


#toTop {
display:none;
text-decoration:none;
position:fixed;
bottom:10px;
right:10px;
overflow:hidden;
width:51px;
height:51px;
border:none;
text-indent:-999px;
background:url(http://3.bp.blogspot.com/-ZaFk139_d7Q/ThWy56hQTtI/AAAAAAAAEtc/i7lYDE7NQRY/s1600/ui.totop.png) no-repeat left top;
}
#toTopHover {
background:url(http://3.bp.blogspot.com/-ZaFk139_d7Q/ThWy56hQTtI/AAAAAAAAEtc/i7lYDE7NQRY/s1600/ui.totop.png) no-repeat left -51px;
width:51px;
height:51px;
display:block;
overflow:hidden;
float:left;
opacity: 0;
-moz-opacity: 0;
filter:alpha(opacity=0);
}
#toTop:active, #toTop:focus {
outline:none;
}

Note - To move the button to the left of your blog change right:10px; to left:10px; .

Step 4. Find the following piece of code in your blogs Html : (Click Ctrl and F for a search bar to help find the code - How To Find Code In Blogger Template Template)

</head>

Step 5. Now Copy And Paste This Code Directly Above / Before </head>

Note - If you have previously added jQuery script to your template you can leave out the line in green.
<script src='http://code.jquery.com/jquery-1.6.1.min.js' type='text/javascript'/>
<script src='http://suyb.googlecode.com/files/jquery.easing.1.3.js' type='text/javascript'/>
<script src='http://suyb.googlecode.com/files/jquery.ui.totop.js' type='text/javascript'/>
<script type='text/javascript'>
$(document).ready(function() {
/*
var defaults = {
containerID: &#39;moccaUItoTop&#39;, // fading element id
containerHoverClass: &#39;moccaUIhover&#39;, // fading element hover class
scrollSpeed: 1200,
easingType: &#39;linear&#39;
};
*/

$().UItoTop({ easingType: &#39;easeOutQuart&#39; });

});
</script>

Step 6. Save your template.

That's it, You can check out your new back to top button after you Comment on and Share this post ! Make sure to check out more of our jQuery Tutorials and Blogger Tips.

Drop Your Comments And Questions Below.



http://www.spiceupyourblog.com/2011/07/jquery-scroll-to-top-button-smooth.html
by Anna 안나 2012. 1. 16. 14:45

This jQuery plugin allows you to set a number of sidebar or floating boxes that follow the user down the page as they scroll. The plugin uses absolute positioning calculated from the original css and offset to either the closest positioned parent or to the document. The plugin has been tested in IE6-9 and all the other major browsers.

The JavaScript (jQuery)

Below is the code for the plugin, to download the code with examples use the link above.

(function($){

  var settings = {
        speed: 350 //animation duration
      , easing: "linear" //use easing plugin for more options
      , padding: 10
      , constrain: false
    }
    , $window = $(window)
    , stickyboxes = []
    , methods = {

          init:function(opts){
            settings = $.extend(settings,opts);
            return this.each(function () {
              var $this = $(this);
              setPosition($this);
              stickyboxes[stickyboxes.length] = $this;
              moveIntoView();
            });
          }

        , remove:function(){
            return this.each(function () {
              var sticky = this;
              $.each(stickyboxes, function (i, $sb) {
                if($sb.get(0) === sticky){
                reset(null, $sb);
                stickyboxes.splice(i, 1);
                return false;
                }
              });
            });
          }

        , destroy: function () {
            $.each(stickyboxes, function (i, $sb) {
              reset(null, $sb);
            });
            stickyboxes=[];
            $window.unbind("scroll", moveIntoView);
            $window.unbind("resize", reset);
            return this;
          }

      };


  var moveIntoView = function () {
    $.each(stickyboxes, function (i, $sb) {
      var $this = $sb
        , data = $this.data("stickySB");
      if (data) {
        var sTop = $window.scrollTop() - data.offs.top
          , currOffs = $this.offset()
          , origTop = data.orig.offset.top - data.offs.top
          , animTo = origTop;
        //scrolled down out of view
        if (origTop < sTop) {
//make sure to stop inside parent
          if ((sTop + settings.padding) > data.offs.bottom)
            animTo = data.offs.bottom;
          else animTo = sTop + settings.padding;
        }
        $this
          .stop()
          .animate(
              {top: animTo}
            , settings.speed
            , settings.easing
        );
      }
    });
  }

  var setPosition = function ($sb) {
    if ($sb) {
      var $this = $sb
        , $parent = $this.parent()
        , parentOffs = $parent.offset()
        , currOff = $this.offset()
        , data = $this.data("stickySB");
      if (!data) {
        data = {
            offs: {} // our parents offset
          , orig: { // cache for original css
                top: $this.css("top")
              , left: $this.css("left")
              , position: $this.css("position")
              , marginTop: $this.css("marginTop")
              , marginLeft: $this.css("marginLeft")
              , offset: $this.offset()
            }
        }
      }
      //go up the tree until we find an elem to position from
      while (parentOffs && "top" in parentOffs
        && $parent.css("position") == "static") {
        $parent = $parent.parent();
        parentOffs = $parent.offset();
      }
      if (parentOffs) { // found a postioned ancestor
        var padBtm = parseInt($parent.css("paddingBottom"));
        padBtm = isNaN(padBtm) ? 0 : padBtm;
        data.offs = parentOffs;
        data.offs.bottom = settings.constrain ?
          Math.abs(($parent.innerHeight() - padBtm) - $this.outerHeight()) :
          $(document).height();
      }
      else data.offs = { // went to far set to doc
          top: 0
        , left: 0
        , bottom: $(document).height()
      };
      $this.css({
          position: "absolute"
        , top: Math.floor(currOff.top - data.offs.top) + "px"
        , left: Math.floor(currOff.left - data.offs.left) + "px"
        , margin: 0
        , width: $this.width()
      }).data("stickySB", data);
    }
  }

  var reset = function (ev, $toReset) {
    var stickies = stickyboxes;
    if ($toReset) { // just resetting selected items
      stickies = [$toReset];
    }
    $.each(stickies, function(i, $sb) {
      var data = $sb.data("stickySB");
      if (data) {
        $sb.css({
            position: data.orig.position
          , marginTop: data.orig.marginTop
          , marginLeft: data.orig.marginLeft
          , left: data.orig.left
          , top: data.orig.top
        });
        if (!$toReset) { // just resetting
          setPosition($sb);
          moveIntoView();
        }
      }
    });
  }

  $window.bind("scroll", moveIntoView);
  $window.bind("resize", reset);

  $.fn.stickySidebar = function (method) {

    if (methods[method]) {
      return methods[method].apply(
          this
        , Array.prototype.slice.call(arguments, 1)
      );
    } else if (!method || typeof method == "object") {
      return methods.init.apply(this, arguments);
    }

  }

})(jQuery);

Usage

The plugin can be used for single or multiple boxes as shown in the examples below

A Single sticky sidebar

1
2
3
4
5
6
7
8
9
10
11
12
13
<div id="main">
  <h2>Product catalogue</h2>
  <ul id="products">
      [...]
  </ul>
</div>
<div id="side">
   <div id="basket">
     <h3>Your basket</h3>
     <p>Total: <strong>&pound;455.00</strong></p>
     <span id="items">4</span>
   </div>
</div>

For the above snippet of a HTML page we can use the following to enable the product basket as a sticky sidebar with the default options.

1
$('#basket').stickySidebar();

Multiple sticky boxes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<div id="left">
  <h2>Left column</h2>
  <ol id="navbox" class="stickybox">
    <li><a href="#">Home</a></li>
    <li><a href="#">About</a></li>
    <li><a href="#">Contact</a></li>
  </ol>
</div>
<div id="middle"></div>
  <div id="right">
    <h2>Right column</h2>
    <div id="basket" class="stickybox">
      <h3>Your basket</h3>
      <p>Total: <strong>&pound;455.00</strong></p>
      <span id="items">4</span>
    </div>
</div>

For the above example we can use the below to set the navbox and basket boxes to both be sticky sidebars with the same options.

1
$('.stickbox').stickySidebar({speed: 400, padding: 30, constrain: true})

Options

The Sticky Sidebar plugin has four options:

  1. speed – how long the animation of the box should take in milliseconds (default = 250)
  2. easing – what type of easing to use for the animation (default = “linear”)
  3. padding – how many pixels to pad the element from the top of the window (default = 10)
  4. constrain – if true stops sticky scrolling out of parent

Methods

The Sticky Sidebar plugin has two methods:

  1. remove – removes the sticky selected sticky sidebars and resets to original position
  2. destroy – removes and resets all sticky sidebars and removes event listeners


http://www.profilepicture.co.uk/tutorials/sticky-sidebar-jquery-plugin/

by Anna 안나 2012. 1. 16. 14:44

영어지만 잘 설명된 글이 있다 : position:fixed for internet explorer

원리 설명이 잘 돼 있는 듯하다.

그리고 관련 토론은 여기서 볼 수 있다 : 떠다니는 레이어, 그 표준은?

아래는 내가 구현한 것이다.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$(document).ready(function(){
    var currentPosition = parseInt($(".float").css("top"));
    $(window).scroll(function() {
        var position = $(window).scrollTop(); // 현재 스크롤바의 위치값을 반환합니다.
        if(position>600){
            if($.browser.msie && $.browser.version < 7){
                $(".float").stop().animate({"top":position+currentPosition-600+"px"},1000);
            }else{
                $(".float").css({'position':'fixed', 'top':'20px'});
            }
        }else{
            $('.float').attr('style','');
        }
    });
});

위 코드는 어느 정도까지는 fixed돼 있지 않다가 스크롤을 좀 내리면 fixed 시키는 코드다. 이를 위해서 꼭 알아야 할 매서드는 scrollTop() 이다. jQuery의 매서드다.

$(window).scrollTop() : 현재 스크롤바의 위치를 반환한다. 정수값을 반환하게 된다.

$(window).scroll(function(){ /*함수 구현부*/ }) : 이 코드는 웹브라우저가 스크롤될 때 실행할 함수를 써 주는 부분이다. 위에서 보면 알겠지만 모든 함수 구현부가 바로 이 안에 인수로 들어가 있다.

function(){/*함수 구현부*/} 형식의 인수는 익명함수라고 한다. 특별한 함수 이름 없이 즉각 함수를 인자값처럼 넘길 수 있는 방식이다. 자바스크립트의 특징이라고 알고 있다.

위 코드가 jQuery쪽 코드고, HTML 쪽에는

?
1
<div class="float">나는 떠다니는 레이어</div>

이런 놈을 넣어 주면 되겠다.

msie 버전 6 이하에서는 position: fixed를 사용할 수 없기 때문에 jQuery의 animate 매서드를 이용해서 처리한다. 1000이라고 써 있는 부분은 동작이 일어나는 시간이다. 1000이 1초다. 이 시간을 늘리면 느리게 움직이고, 줄이면 빠르게 움직이다. 0으로 하면 순간이동을 하는데, 좋지가 않다.

position이 600보다 작을 때는 $('.float').attr('style','') 이라고 코드를 써 놨는데, 요소 스타일을 제거해 버리는 코드다. 그러면 jQuery를 이용해 임의로 매긴 스타일이 모두 사라진다. 단, 이를 위해서는 기본 스타일은 모두 css 파일에 담아 두어야 한다. 그렇지 않으면 기본 스타일로 박아 놓은 것도 함께 날아갈 테니 말이다.

시간이 없어서 친절한 설명을 하지 못해 아쉽다. 하지만 코드를 잘 분석하면 충분히 이해할 수 있을 거라 생각한다.


http://mytory.co.kr/archives/761

by Anna 안나 2012. 1. 16. 14:43
트윗을 보던 중, 쿠나님이 티스토리 블로그에 아약스를 적용하고 있다는 것을 발견했다.

음..

이란 생각과 함께 바로 가서 구경!


읭..

귀찮아서 하기 싫었던건데 막상 보니까 무진장 하고 싶어졌다. ㅋㅋㅋ


그래서 바로 적용 시도.




일단 몇가지 문제가 있다.

1. SyntaxHighlight와 FootNote 등 BLUEnLIVE 님이 적용해두신 스크립트가 먹지 않는다.
뭐 해결하려면 하겠는데 일단 당장은 귀찮으니 패스.
툴팁은 일단 여기를 참고해보도록 하자..

2. TC용 플러그인은 해당 플러그인을 직접 수정해야한다.

3. 카테고리.. [...]
이.. 이건.. 답이 없는듯;;




텍스트큐브 1.8.4엔 기본적으로 jQuery 1.4가 들어간다.
그러니 scrollTo 파일만 넣도록 하자.

scrollTo.js는 여기에서 받을 수 있다.

아 깜빡한게 있군.
로딩 인디케이터는 여기에서 직접 만들 수 있다.



그리고 아래 소스를 head 태그 안이든 적당한 곳에 넣어둔다.

<!-- deVbug.me Ajax -->
<script type="text/javascript" src="/resources/script/jquery/jquery.scrollTo-1.4.2-min.js"></script>
<script language="javascript">
function LoadPage(url)
{
	if (url == "" || typeof url == "undefined" || url == null) return;

	jQuery.scrollTo( 0, 800, {queue:true} );

	jQuery("#content").html("<center><img src='./ajax-loader.gif'></center>");

	jQuery.get(url, function(data) {
		jQuery('#content').html(jQuery(data).find('#content').html());

		jQuery("div.tagTrail a").click(function() {
			LoadPage(this.href); return false;
		});

		var dest_id = url.substring(url.indexOf("#"));
		jQuery.scrollTo( jQuery(dest_id), 800, {queue:true} );
	});
}
</script>







텍스트큐브나 티스토리나 이런 부분은 거의 같아서 쿠나님의 글과 별반 다를게 없다.




주요 a 태그에 다음 내용을 추가한다.

 onclick="LoadPage(this.href); return false;"




블로그 제목, 상단 메뉴 등과 같은 곳이겠지.

이후 스킨 파일에서 href로 검색해서 나오는 곳을 확인하며 일일히 추가해주면 된다.
특히 새로 올라온 글 부분 등.


Paging 부분은 다음처럼 한다.


<s_paging>
	<div id="paging">
		<a  title="이전" class="" id="prevPage" onclick="LoadPage(this.href); return false;">« Prev </a> :
		<s_paging_rep> <a  class="num" onclick="LoadPage(this.href); return false;"></a> : </s_paging_rep>
		<a  title="다음" class="" id="nextPage" onclick="LoadPage(this.href); return false;">Next »</a> 
	</div>
</s_paging>



역시 다를게 없군.




사이드바에서 검색 부분은 아래처럼 하자.


<!-- 검색 -->
<div id="searchBox">
	<s_search>
		<input type="text" name="" value="" onkeypress="if (event.keyCode == 13) { LoadPage('/search/'+this.value); return false; }"/>
		<input value="검색" type="button" onclick="LoadPage('/search/'+document.getElementsByName('')[0].value); return false;" class="submit"/>
	</s_search>
</div>





새로 등록된 댓글, 트랙백 등과 같은 곳에도 똑같이 집어넣으면 알아서 이동하고 스크롤도 된다.




이걸 플러그인 형태로 만들어야 했을텐데 이미 귀찮아서 이따위로 만들어버렸으니.. 떫..

에효 암튼 무엇보다 문법 강조 플러그인이나 제대로 작동하게 조만간 우선 작업해야겠다.
아주 개판으로 나오겠지. ㅠㅠ



아 그리고, 이 외에 수정한 플러그인은, 나같은 경우
FootNote, JP_ArchiveSelectboxTT, MT_Meta_RecentPS_Default 이고..
JP_ShortenEntryContentsTT 는 수정해도 제대로 작동을 안 하네..

http://devbug.me/561
by Anna 안나 2012. 1. 16. 14:41
간단히 말해서 페이지 갱신을 하지 않고 내용 갱신을 하는 것인데 (아니 말이 이상하네) ... 제일 좋은 예제는 http://www.happyfri.com/blog/ 블로그를 참조하시면 됩니다 (사실 이거 때문에 전 끌려서.. 에헤헤)

별도로 소개할 수 있는 내용이 없으니 스샷은 없고, 저도 적용은 더욱 심화하는것보다 이정도에서 끝내려고 합니다(위젯 덕지덕지인 브롤그에 쓰시면 좋을것 같네요). 그런고로, 일반적 스킨에서 적용할 수 있는 적용 방법을 간단히 적어놓고 ... 그렇게 오늘의 삽질, 종료! [절대 학생회의 일존이라던가를 따라하지 않았습니다]

1. jQuery 프레임워크 와 scrollTo 확장 플러그인 자바스크립트 파일 및 로딩 시에 쓰일 이미지를 티스토리에 올려봅시다. 귀찮으니까 제가 손수 준비한 파일을 쓰시면........ 되겠지요. (물론 scrollTo의 저작권은 여기에, jQuery의 저작권은 여기에, 로딩 이미지는 여기에 저작권이 있음을 알립니다아)


2. <head>~</head> 사이의 적당한 곳에 이 코드를 넣습니다.
<!-- AJAX Part -->
<script src="./images/jquery-1.4.2.min.js" language="javascript"></script>
<script src="./images/jquery.scrollTo-min.js" language="javascript"></script>
<script language="javascript">
function loadPage(url) {
$("#content").html("<center><img src='./images/ajax-loader.gif'></center>");
$.scrollTo( $('#content'), 800 );
var dest_url = url.substring(0, url.indexOf("#"));
if (dest_url == "") dest_url = url;
$.get(dest_url, function(data) {
var obj = $(data);
var ihtml = obj.find("#content").html();
$("#content").html(ihtml);

var dest_id = url.substring(url.indexOf("#"));
$.scrollTo( $(dest_id), 800, {queue:true} );
});
}

function loadPage_paging(paging_url) {
var url = paging_url.href;
loadPage(url);
}
</script>


3. 보시면 아시겠지만, loadPage라는 함수를 이용해서 사용이 가능합니다.
(1) 검색 위젯 부분
<s_search>
<input type="text" name="[ ##_search_name_## ]" value="[ ##_search_text_## ]" onkeypress="if (event.keyCode == 13) { loadPage('/search/' + document.getElementsByName('search')[0].value.replaceAll('%', '%25')); }"/>
<input value="search" type="button" onclick="loadPage('/search/' + document.getElementsByName('search')[0].value.replaceAll('%', '%25'));" class="submit"/>
</s_search>

(2) 최근 포스트 위젯 부분
<a href="[ ##_rctps_rep_link_## ]" onclick="loadPage('[ ##_rctps_rep_link_## ]'); return false;"> [ ##_rctps_rep_title_## ]</a>
*deVbug님이 내주신 좋은 코드 덕택에 최근 덧글/최근 트랙백 모듈에도 사용가능합니다! 해당 코드는 위에 새로 넣어놓은 상태이고요, deVbug님, 감사합니다~! 

(3) 방명록 같은 메뉴 부분
<a href="[ ##_guestbook_link_## ]" onclick="loadPage('[ ##_guestbook_link_## ]'); return false;">guestbook</a> 

사용법은 보시면 아시겠지만 간단하게 onclick="loadPage('[이동할 URL]') return false;"이면 된다는 것을 알 수 있습니다.

또, 그리고 만들어 놓은 추가 함수로 이렇게 사용이 가능합니다.
(4) 하단의 페이징 부분
<s_paging>
<div class="paging">
<a [ ##_prev_page_## ] onclick="loadPage_paging(this); return false;" class="[ ##_no_more_prev_## ]">&lt;&lt; previous </a>
<span class="numbox">
<s_paging_rep>
<a [ ##_paging_rep_link_## ] onclick='loadPage_paging(this); return false;' class="num"> [ ##_paging_rep_link_num_## ]</a>
</s_paging_rep>
</span>
<a [ ##_next_page_## ] onclick="loadPage_paging(this); return false;" class="[ ##_no_more_next_## ]">next &gt;&gt;</a>
</div>
</s_paging>


물론 해보고싶으신 분들만 백업 철저히 해놓고 마음대로 하세요.
난 옛날처럼 시간이 남아나지 않으니까 A/S는 직접 보고서 해줄 분들만 해줄꺼에요.

http://kuna.wo.tc/1220
by Anna 안나 2012. 1. 16. 14:40
이전에 문제가 되었던 UIScrollView에서의 page detecting을 해결하기 위해 구글링 도중에 page의 lazy loading을 고민하는 사람이 많다는 것을 알게 되었다. 이는 지금 나같이 너댓장의 이미지를 로딩하는 데에는 큰 문제가 되지 않지만 수십 수백장의 이미지 혹은 다른 그 어떤 것을 로딩하기 에는 좀 문제가 된다.
원래대로라면 하나의 scrollview에 수십 수백장의 imageview를 addSubview를 이용해 추가하는 것인데 당연히 퍼포먼스나 메모리 관리 측면에서 문제가 안될리 없다. 그래서 많은 image gallery 어플이 하는 방식인 현재 보이는 view와 그 이전/이후의 view만을 로딩하는 lazy loading 방식에 대해 찾아 보다가 stack overflow에서 아래의 sample code를 발견했다.
먼저 interface 부분.
01.@interface UntitledViewController : UIViewController<UIScrollViewDelegate> {
02.@private
03.UIScrollView *_scrollView;
04. 
05.NSArray *_objects;
06. 
07.UILabel *_detailLabel1;
08.UILabel *_detailLabel2;
09.UILabel *_detailLabel3;
10.}
11. 
12.- (void)replaceHiddenLabels;
13.- (void)displayLabelsAroundIndex:(NSInteger)index;
14. 
15.@end

그리고 실제 구현 부분.
001.@implementation UntitledViewController
002. 
003.- (void)dealloc
004.{
005.[_objects release];
006.[_scrollView release];
007.[_detailLabel1 release];
008.[_detailLabel2 release];
009.[_detailLabel3 release];
010.[super dealloc];
011.}
012. 
013.- (void)viewDidLoad
014.{
015.[super viewDidLoad];
016. 
017._objects = [[NSArray alloc] initWithObjects:@"first", @"second", @"third",
018.@"fourth", @"fifth", @"sixth", @"seventh", @"eight", @"ninth", @"tenth", nil];
019. 
020._scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 460.0)];
021._scrollView.contentSize = CGSizeMake(320.0 * [_objects count], 460.0);
022._scrollView.showsVerticalScrollIndicator = NO;
023._scrollView.showsHorizontalScrollIndicator = YES;
024._scrollView.alwaysBounceHorizontal = YES;
025._scrollView.alwaysBounceVertical = NO;
026._scrollView.pagingEnabled = YES;
027._scrollView.delegate = self;
028. 
029._detailLabel1 = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 460.0)];
030._detailLabel1.textAlignment = UITextAlignmentCenter;
031._detailLabel1.font = [UIFont boldSystemFontOfSize:30.0];
032._detailLabel2 = [[UILabel alloc] initWithFrame:CGRectMake(320.0, 0.0, 320.0, 460.0)];
033._detailLabel2.textAlignment = UITextAlignmentCenter;
034._detailLabel2.font = [UIFont boldSystemFontOfSize:30.0];
035._detailLabel3 = [[UILabel alloc] initWithFrame:CGRectMake(640.0, 0.0, 320.0, 460.0)];
036._detailLabel3.textAlignment = UITextAlignmentCenter;
037._detailLabel3.font = [UIFont boldSystemFontOfSize:30.0];
038. 
039.// We are going to show all the contents of the _objects array
040.// using only these three UILabel instances, making them jump
041.// right and left, replacing them as required:
042.[_scrollView addSubview:_detailLabel1];
043.[_scrollView addSubview:_detailLabel2];
044.[_scrollView addSubview:_detailLabel3];
045. 
046.[self.view addSubview:_scrollView];
047.}
048. 
049.- (void)viewDidAppear:(BOOL)animated
050.{
051.[super viewDidAppear:animated];
052.[_scrollView flashScrollIndicators];
053.}
054. 
055.- (void)viewWillAppear:(BOOL)animated
056.{
057.[super viewWillAppear:animated];
058.[self displayLabelsAroundIndex:0];
059.}
060. 
061.- (void)didReceiveMemoryWarning
062.{
063.// Here you could release the data source, but make sure
064.// you rebuild it in a lazy-loading way as soon as you need it again...
065.[super didReceiveMemoryWarning];
066.}
067. 
068.#pragma mark -
069.#pragma mark UIScrollViewDelegate methods
070. 
071.- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
072.{
073.// Do some initialization here, before the scroll view starts moving!
074.}
075. 
076.- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
077.{
078.[self replaceHiddenLabels];
079.}
080. 
081.- (void)displayLabelsAroundIndex:(NSInteger)index
082.{
083.NSInteger count = [_objects count];
084.if (index >= 0 && index < count)
085.{
086.NSString *text = [_objects objectAtIndex:index];
087._detailLabel1.frame = CGRectMake(320.0 * index, 0.0, 320.0, 460.0);
088._detailLabel1.text = text;
089.[_scrollView scrollRectToVisible:CGRectMake(320.0 * index, 0.0, 320.0, 460.0) animated:NO];
090. 
091.if (index < (count - 1))
092.{
093.text = [_objects objectAtIndex:(index + 1)];
094._detailLabel2.frame = CGRectMake(320.0 * (index + 1), 0.0, 320.0, 460.0);
095._detailLabel2.text = text;
096.}
097. 
098.if (index > 0)
099.{
100.text = [_objects objectAtIndex:(index - 1)];
101._detailLabel3.frame = CGRectMake(320.0 * (index - 1), 0.0, 320.0, 460.0);
102._detailLabel3.text = text;
103.}
104.}
105.}
106. 
107.- (void)replaceHiddenLabels
108.{
109.static const double pageWidth = 320.0;
110.NSInteger currentIndex = ((_scrollView.contentOffset.x - pageWidth) / pageWidth) + 1;
111. 
112.UILabel *currentLabel = nil;
113.UILabel *previousLabel = nil;
114.UILabel *nextLabel = nil;
115. 
116.if (CGRectContainsPoint(_detailLabel1.frame, _scrollView.contentOffset))
117.{
118.currentLabel = _detailLabel1;
119.previousLabel = _detailLabel2;
120.nextLabel = _detailLabel3;
121.}
122.else if (CGRectContainsPoint(_detailLabel2.frame, _scrollView.contentOffset))
123.{
124.currentLabel = _detailLabel2;
125.previousLabel = _detailLabel1;
126.nextLabel = _detailLabel3;
127.}
128.else
129.{
130.currentLabel = _detailLabel3;
131.previousLabel = _detailLabel1;
132.nextLabel = _detailLabel2;
133.}
134. 
135.currentLabel.frame = CGRectMake(320.0 * currentIndex, 0.0, 320.0, 460.0);
136.currentLabel.text = [_objects objectAtIndex:currentIndex];
137. 
138.// Now move the other ones around
139.// and set them ready for the next scroll
140.if (currentIndex < [_objects count] - 1)
141.{
142.nextLabel.frame = CGRectMake(320.0 * (currentIndex + 1), 0.0, 320.0, 460.0);
143.nextLabel.text = [_objects objectAtIndex:(currentIndex + 1)];
144.}
145. 
146.if (currentIndex >= 1)
147.{
148.previousLabel.frame = CGRectMake(320.0 * (currentIndex - 1), 0.0, 320.0, 460.0);
149.previousLabel.text = [_objects objectAtIndex:(currentIndex - 1)];
150.}
151.}
152. 
153.@end

언더바를 많이 쓰고 대괄호 쓰는 방식이 C 프로그래밍 스타일이라 좀 별로지만 그대로 옮겨왔다. 수정하기 귀찮... 하여간 이 코드를 그대로 갖다 복사해도 동작한다. scrollview에 각각 label을 붙이는 subview를 만들어서 한번에 세개의 view를 로딩하고 스크롤할 때마다 다시 그 다음 것들을 loading하는 방식이다.

그리고 추가로 저 위의 scrollViewDidEndDecelerating 메소드 안에 아래의 코드를 갖다 붙이면 현재 보이는 page를 알아낼 수 있다.

1.int page = floor((_scrollView.contentOffset.x - PAGE_WIDTH / 2) / PAGE_WIDTH) + 1;

http://yangsae.tistory.com/38
by Anna 안나 2012. 1. 16. 14:39
mixsh나 twtkr등에서 스크를 마지막에 가면 자동으로 다음 글들을 불러 오게 하는 자료입니다.
JQUERY로 짜여졌고 간단합니다.

엄청나게 간단하네요....;;;

링크에 실제 배포하는 사이트 남겨 두었습니다.

샘플보기(스크롤해서 내려 보세요) :
http://www.webresourcesdepot.com/dnspinger/


구조설명:

컨텐츠 페이지 구조
<div class="wrdLatest" id=1>content</div>
<div class="wrdLatest" id=2>content</div>
<div id="lastPostsLoader"></div>

로딩중 이미지 보여주는 부분과 실제 데이터 가져오는 부분
function lastPostFunc()
{
    $('div#lastPostsLoader').html('<img src="bigLoader.gif">');
    $.post("scroll.asp?action=getLastPosts&lastID=" + $(".wrdLatest:last").attr("id"),   


    function(data){
        if (data != "") {
        $(".wrdLatest:last").after(data);           
        }
        $('div#lastPostsLoader').empty();
    });
};

스크롤 감지하는 부분
$(window).scroll(function(){
        if  ($(window).scrollTop() == $(document).height() - $(window).height()){
          lastPostFunc();
        }
});

http://dev.dayis.net/17
by Anna 안나 2012. 1. 16. 14:38
블로그를 한창 할때, 믹시의 스크롤 페이징을 보고서 어떻게 하는 건지 참 많이 궁금해 했던 기억이 납니다. 
졸립기도 하고 갑자기 스크롤 페이징이 생각 나서 검색해봤는데 쭌스님의 포스팅과 Raj Gorsia님의 포스팅을 찾게 되었습니다. 스크립트 라이브러리를 사용하지 않는다면 쭌스님의 글을 참고해서 작성하면 되겠고 JQuery를 사용한다면 Raj Gorsia님의 글을 거의 그대로 사용하면 되겠네요.

예전에 제가 감을 잡지 못 했던 부분은 아래 한줄입니다. ㅠ.ㅠ
if ($(window).scrollTop() == $(document).height() - $(window).height()) { 
또는
if(content.scrollTop < content.scrollHeight - 500)
이렇게 간단한데 말이죠... 

지금은 응용할만한 프로그램을 만들지 않지만 다음에 꼭 활용해서 만들어 보고 싶네요. 


 
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=euc-kr" />
<title>JQuery</title>
<link rel="stylesheet" type="text/css" href="css.css"/>
<script type="text/javascript" src="jquery-1.6.min.js"></script>
<script type="text/javascript">
//<![CDATA[
var pageLoaded = 1; //현재 페이지

$(window).scroll( function() {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
pageLoaded = pageLoaded + 1; 
// ajax를 추가해서 목록을 받아온다
// alert(pageLoaded);
$('#main_content').append(
"main_content"+pageLoaded+"<br><br><br><br><br><br><br><br><br><br><br><br><br>");
}
});
//]]>
</script>

<style type="text/css">

</style>

</head>
<body>
<div id="top_menu">
<ul id="topUL">
<li class="to_home"><a href="/">HOME</a></li>
<li class="top_menu_li" id="login_btn">로그인</li>
<li class="top_menu_li"> | </li>
<li class="top_menu_li" id="join_btn">회원가입</li>
</ul>
</div>
<div id="wrap">
<div id="left_menu">left_menu</div>
<div id="content">
<div id="login_box">login_box</div>
<div id="join_box">join_box</div>
<div id="main_content">
main_content1<br><br><br><br><br><br><br><br><br><br><br><br><br>
main_content2<br><br><br><br><br><br><br><br><br><br><br><br><br>
main_content3<br><br><br><br><br><br><br><br><br><br><br><br><br>
main_content4<br><br><br><br><br><br><br><br><br><br><br><br><br>
main_content5<br><br><br><br><br><br><br><br><br><br><br><br><br>
</div>
</div>
<div id="right_menu">right_menu</div>
</div>
</body>
</html>

참조 1 : 스크롤 페이징(Scroll Paging, Continuous scrolling pattern)
참조 2 : Load Content While Scrolling With jQuery

http://www.rtong.net/1148
by Anna 안나 2012. 1. 16. 14:37
http://net.tutsplus.com/tutorials/javascript-ajax/inettuts/

Finished Project

The plan

First, let's list exactly what we'll be creating here and what features it'll have:

  • This interface will contain several widgets.
  • Each widget can be collapsed, removed and edited.
  • The widgets can be sorted into the three seperate columns by the user (using a drag and drop technique).
  • The user will be able to edit the color and title of each widget.
  • Each widget can contain any amount of regular HTML content, text, images, flash etc.

Please note that we will only be covering the front-end aspect of the project in this tutorial. Obviously you could integrate this UI with a solid server-side system which could take care of saving preferences and customised widgets.

Since it's all about the user and because the idea was influenced by iGoogle we're going to be calling this project 'iNettuts'.

The layout of iNettuts

The layout is a simple three column one; each column contains widgets:

layout

Each widget has a "handle" which the user can use to move the widget around.

jQuery UI

As well as the jQuery core library we're also going to make use of the jQuery's UI library and specifically the "sortable" and "draggable" modules. This will make it quite simple to add the drag-and-drop functionality that we want. You should get a personalized download of the UI library which has what we need in it. (Tick the 'sortable' box)

Step 1: XHTML markup

Each column will be an unordered list (UL) and each widget within the columns will be a list item (LI):

First column:

  1. <ul id="column1" class="column">  
  2.   
  3.     <li class="widget red">    
  4.         <div class="widget-head">  
  5.             <h3>Widget title</h3>  
  6.         </div>  
  7.         <div class="widget-content">  
  8.   
  9.             <p>The content...</p>  
  10.         </div>  
  11.     </li>  
  12.     <li class="widget blue">    
  13.         <div class="widget-head">  
  14.   
  15.             <h3>Widget title</h3>  
  16.         </div>  
  17.         <div class="widget-content">  
  18.             <p>The content...</p>  
  19.   
  20.         </div>  
  21.     </li>  
  22. </ul>  

The above code represents the first column, on the left and two widgets each within a list item. As shown in the plan, there will be three columns - three unordered lists.

Step 2: CSS

We'll be using two CSS StyleSheets, one of them will contain all the main styles and the second StyleSheet will only contain styles required by the JavaScript enhancements. The reason we seperate them like this is so that people without JavaScript enabled do not waste their bandwidth downloading styles which they're not going to use.

Here is inettuts.css:

  1. /* Reset */  
  2. body,img,p,h1,h2,h3,h4,h5,h6,ul,ol {margin:0; padding:0; list-style:noneborder:none;}  
  3. /* End Reset */  
  4.       
  5. body {font-size:0.8em; font-family:Arial,Verdana,Sans-Serifbackground#000;}  
  6. a {color:white;}  
  7.       
  8. /* Colours */  
  9. .color-yellow {background:#f2bc00;}  
  10. .color-red    {background:#dd0000;}  
  11. .color-blue   {background:#148ea4;}  
  12. .color-white  {background:#dfdfdf;}  
  13. .color-orange {background:#f66e00;}  
  14. .color-green  {background:#8dc100;}  
  15. .color-yellow h3,.color-white h3,.color-green h3  
  16.     {color:#000;}  
  17. .color-red h3,.color-blue h3,.color-orange h3  
  18.     {color:#FFF;}  
  19. /* End Colours */  
  20.       
  21. /* Head section */  
  22. #head {  
  23.     background#000 url(img/head-bg.png) repeat-x;  
  24.     height100px;  
  25. }  
  26. #head h1 {  
  27.     line-height100px;  
  28.     color#FFF;  
  29.     text-aligncenter;  
  30.     backgroundurl(img/inettuts.png) no-repeat center;  
  31.     text-indent: -9999em  
  32. }  
  33. /* End Head Section */  
  34.       
  35. /* Columns section */  
  36. #columns .column {  
  37.     floatleft;  
  38.     width: 33.3%;  
  39.         /* Min-height: */  
  40.         min-height400px;  
  41.         heightauto !important;   
  42.         height400px;  
  43. }  
  44.       
  45. /* Column dividers (background-images) : */  
  46.     #column#column1 { backgroundurl(img/column-bg-left.png) no-repeat rightright top; }  
  47.     #column#column3 { backgroundurl(img/column-bg-rightright.png) no-repeat left top; }  
  48.           
  49. #column#column1 .widget { margin30px 35px 30px 25px; }  
  50. #column#column3 .widget { margin30px 25px 30px 35px; }  
  51. #columns .widget {  
  52.     margin30px 20px 0 20px;  
  53.     padding2px;  
  54.     -moz-border-radius: 4px;  
  55.     -webkit-border-radius: 4px;  
  56. }  
  57. #columns .widget .widget-head {  
  58.     color#000;  
  59.     overflowhidden;  
  60.     width: 100%;  
  61.     height30px;  
  62.     line-height30px;  
  63. }  
  64. #columns .widget .widget-head h3 {  
  65.     padding: 0 5px;  
  66.     floatleft;  
  67. }  
  68. #columns .widget .widget-content {  
  69.     background#333 url(img/widget-content-bg.png) repeat-x;  
  70.     padding5px;  
  71.     color#DDD;  
  72.     -moz-border-radius-bottomleft: 2px;  
  73.     -moz-border-radius-bottomright: 2px;  
  74.     -webkit-border-bottom-left-radius: 2px;  
  75.     -webkit-border-bottom-rightright-radius: 2px;  
  76.     line-height: 1.2em;  
  77.     overflowhidden;  
  78. }  
  79. /* End Columns section */  

There's nothing too complicated in the above StyleSheet. Normally it would be better to use images instead of the CSS3 border-radius property to create rounded corners (for cross-browser benefits) but they're not really an integral part of the layout - adding a border-radius is quick and painless.

Just a note about the colour classes: Ideally, elements should be named according to their semantic meaning or content, not their appearance. The problem is that the widgets can mean/contain many different things so having classes like this really is the best alternative, unless you're willing to add the colour styles inline. Each colour class is prefixed with 'color-'; it'll become clear why I've done this later in the tutorial.

In the above CSS we're also using a min-height hack for each column so that the background images (the dividers) remain intact and so that an empty column can still have widgets dragged back into it:

  1. #columns .column {  
  2.     floatleft;  
  3.     width: 33.3%;  
  4.       
  5.     /* Min-height: */  
  6.         min-height400px;  
  7.         heightauto !important;   
  8.         height400px;  
  9. }  

We'll focus on the second stylesheet later when we've added the JavaScript.

Here's a preview of what we've got so far, just CSS/HTML (and some images):

layout

Step 3: JavaScript

Introduction

As I've said, we'll be using jQuery. It's the library of choice not only because of the UI modules it offers but also because it will help in speeding up the development process while keeping everything cross-browser operable.

The final product will have endless possibilities, some of which have already been explored by the likes of NetVibes and iGoogle. So, we want to make sure our code is easily maintainable, allows for expandability and is reusable; we want it to be future-proof!

We'll begin with a global object called "iNettuts" - this will act as the sole occupied namespace of the project (plus dependencies such as jQuery). Under it we will code up the main functionality of the site which utilises jQuery and its UI library.

inettuts.js:

  1. var iNettuts = {  
  2.     settings : {  
  3.        // Some simple settings will go here.  
  4.     },  
  5.     init : function(){  
  6.         // The method which starts it all...  
  7.     }  
  8. };  

The init method will be called when the document is ready for manipulation (i.e. when the DOM is loaded and ready). While there are various methods available it has been proven that the quickest way to initialise your code upon this event is to call it from the bottom of your document. It also makes sense to link to all the scripts at the bottom so as not to slow down the loading of the rest of the page:

  1. <body>  
  2.       
  3.     <!-- page content -->  
  4.   
  5.       
  6.       
  7.     <!-- Bottom of document -->  
  8.     <script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.2.6.min.js"></script>  
  9.     <script type="text/javascript" src="inettuts.js"></script>  
  10.   
  11.     <script type="text/javascript" src="jquery-ui-personalized-1.6rc2.min.js"></script>  
  12.       
  13. </body>  

Settings

As I've said, there will be a settings object which will contain all of the global settings required to make this functional. We'll also have individual widget settings objects, this means it will be possible to create per-widget settings.

settings object (under iNettuts):

  1. settings : {  
  2.     /* Specify selectors */  
  3.     columns : '.column',  
  4.     widgetSelector: '.widget',  
  5.     handleSelector: '.widget-head',  
  6.     contentSelector: '.widget-content',  
  7.     /* Settings for the Widgets: */  
  8.     widgetDefault : {  
  9.         movable: true,  
  10.         removable: true,  
  11.         collapsible: true,  
  12.         editable: true,  
  13.         colorClasses : ['yellow','red','blue','white','orange','green']  
  14.     },  
  15.     /* Individual Widget settings: */  
  16.     widgetIndividual : {  
  17.         intro : {  
  18.             movable: false,  
  19.             removable: false,  
  20.             collapsible: false  
  21.         },  
  22.         gallery : {  
  23.             colorClasses : ['yellow','red','white']  
  24.         }  
  25.     }  
  26. }  

Yes, there are quite a lot of settings, but if we want maximum code reusability this is a necessity. Most of the above is self explanatory. As you can see we've setup a widgetDefault object which contains the default settings for each widget; if you want to override these settings then the script will require you to give the widget an id (in the HTML) and then create a new ruleset. We've got two rule-sets (objects) which override their defaults, 'intro' and 'gallery'. So, those rules specified in the "gallery" object will only apply to this widget:

  1. <li class="widget blue" id="gallery">    
  2.     <div class="widget-head">  
  3.         <h3>Instructions</h3>  
  4.     </div>  
  5.   
  6.     <div class="widget-content">  
  7.         <ul>  
  8.             <li>To move a widget...</li>  
  9.         </ul>  
  10.     </div>  
  11.   
  12. </li>  

Retrieving the settings

getWidgetSettings object (under iNettuts):

  1. getWidgetSettings : function(id) {  
  2.     var settings = this.settings;  
  3.     return (id&&settings.widgetIndividual[id]) ?   
  4.         $.extend({},settings.widgetDefault,settings.widgetIndividual[id])  
  5.         : settings.widgetDefault;  
  6. }  

This method will return an object with the settings of any particular widget. If a widget has no id (HTML attribute) then it will just return the default settings, otherwise it will look to see if that widget has settings of its own, if it does then it will return the default settings and that widget's settings merged into a single object (the widget's individual settings have precedence).

Attaching a CSS file using JavaScript

I mentioned earlier that we have an additional stylesheet which the JavaScript enhancements will require.

Here's the StyleSheet (inettuts.js.css):

  1. /* JS-Enabled CSS */  
  2.       
  3. .widget-head a.remove  {  
  4.     floatrightright;  
  5.     displayinline;  
  6.     backgroundurl(img/buttons.gif) no-repeat -24px 0;  
  7.     width14px;  
  8.     height14px;  
  9.     margin8px 4px 8px 0;  
  10.     text-indent: -9999em;  
  11.     outlinenone;  
  12. }  
  13.       
  14. .widget-head a.edit  {  
  15.     floatrightright;  
  16.     displayinline;  
  17.     backgroundurl(img/buttons.gif) no-repeat;  
  18.     width24px;  
  19.     height14px;  
  20.     text-indent: -9999em;  
  21.     margin8px 4px 8px 4px;  
  22.     outlinenone;  
  23. }  
  24.       
  25. .widget-head a.collapse  {  
  26.     floatleft;  
  27.     displayinline;  
  28.     backgroundurl(img/buttons.gif) no-repeat -52px 0;  
  29.     width14px;  
  30.     height14px;  
  31.     text-indent: -9999em;  
  32.     margin8px 0 8px 4px;  
  33.     outlinenone;  
  34. }  
  35.       
  36. .widget-placeholder { border2px dashed #999;}  
  37. #column1 .widget-placeholder { margin30px 35px 0 25px; }  
  38. #column2 .widget-placeholder { margin30px 20px 0 20px; }  
  39. #column3 .widget-placeholder { margin30px 25px 0 35px; }  
  40.       
  41. .edit-box {  
  42.     overflowhidden;  
  43.     background#333 url(img/widget-content-bg.png) repeat-x;  
  44.     margin-bottom2px;  
  45.     padding10px 0;  
  46. }  
  47.       
  48. .edit-box li.item {  
  49.     padding10px 0;  
  50.     overflowhidden;  
  51.     floatleft;  
  52.     width: 100%;  
  53.     clearboth;  
  54. }  
  55.       
  56. .edit-box label {  
  57.     floatleft;  
  58.     width: 30%;  
  59.     color#FFF;  
  60.     padding: 0 0 0 10px;  
  61. }  
  62.       
  63. .edit-box ul.colors li {  
  64.     width20px;  
  65.     height20px;  
  66.     border1px solid #EEE;  
  67.     floatleft;  
  68.     displayinline;  
  69.     margin: 0 5px 0 0;  
  70.     cursorpointer;  
  71. }  

The elements targetted in the above StyleSheet have yet to be coded, but eventually we will write the JavaScript which dynamically adds these elements to the page, thus making use of the StyleSheet.

The method which attaches this StyleSheet is called 'attachStylesheet':

  1. attachStylesheet : function (href) {  
  2.     return $('<link href="' + href + '" rel="stylesheet" type="text/css" />').appendTo('head');  
  3. }  

The above method appends a link to the head of the document. When a new link element is added to the document through the DOM the browser will load it and apply its CSS rules as it would for any regular hard-coded linked StyleSheet. When doing this, remember that the rules of CSS inheritance and specificity still apply.

Making the widgets work

Widgets

The next part of the tutorial is probably the hardest, so take it slowly.

We want to add another method to our global iNettuts object, we'll call it makeSortable:

  1. makeSortable : function () {  
  2.     // This function will make the widgets 'sortable'!  
  3. }  

By the way, 'method' is just a fancy name given to 'functions' which have been assigned to object properties. In this case our object is called 'iNettuts' so 'makeSortable' is a method of 'iNettuts'...

This new method will take the settings we specified in the 'settings' object and make the required element sortable.

First, we want to make sure everything we need is easily accessible within this new method:

  1. makeSortable : function () {  
  2.     var iNettuts = this// *1  
  3.         $ = this.jQuery, // *2  
  4.         settings = this.settings; // *3  
  5. }  

*1: There will only be one instance of our global object, but just encase multiple instances need to be made or if we want to rename the global object it's a good idea to set a new variable (in this case 'iNettuts') to the 'this' keyword which references the object that this method is within. Be careful, the 'this' keyword is a bit of a beast and doesn't always reference what you think it does!

*2: At the very top of the iNettuts object we've placed a new property: 'jQuery : $'. In the pursuit of maximum code reusability we don't want our script to conflict with any other libraries that also make use of the dollar-sign symbol (e.g. The Prototype library). So, for example, if you renamed jQuery to JQLIB then you could change the 'jQuery' property to JQLIB and the script would continue to function properly. The 2nd line in the above code isn't necessary at all, - if we didn't want it we could just use this.jQuery().ajQueryFunction() instead of $() within this method.

*3: Again, this isn't really necessary, we're just creating a bit of a shortcut, so instead of having to type out 'this.settings' within this method we only need to type out 'settings'.

The next step is to define a set of sortable items (i.e. the widgets that will be movable). Remember, back in the settings we made it possible to set a property called 'movable' to true or false. If 'movable' is set to false, either by default or on individual widgets we have to cater for that:

  1. /* 
  2.  * (using the dollar prefix on $sortableItems is a convention when a variable references a jQuery object) 
  3.  */  
  4.     
  5. $sortableItems = (function () {  
  6.       
  7.     // Define an empty string which can add to within the loop:  
  8.     var notSortable = '';  
  9.       
  10.     // Loop through each widget within the columns:  
  11.     $(settings.widgetSelector,$(settings.columns)).each(function (i) {  
  12.           
  13.         // If the 'movable' property is set to false:  
  14.         if (!iNettuts.getWidgetSettings(this.id).movable) {  
  15.               
  16.             // If this widget has NO ID:   
  17.             if(!this.id) {  
  18.                   
  19.                 // Give it an automatically generated ID:  
  20.                 this.id = 'widget-no-id-' + i;  
  21.                   
  22.             }  
  23.           
  24.             // Add the ID to the 'notSortable' string:  
  25.             notSortable += '#' + this.id + ',';  
  26.         }  
  27.           
  28.     });  
  29.       
  30.     /* 
  31.     * This function will return a jQuery object containing 
  32.     * those widgets which are movable. 
  33.     */  
  34.     return $('> li:not(' + notSortable + ')', settings.columns);  
  35. })();  

Now we've got a set of DOM elements referenced in the jQuery object which is returned from the above functions. We can make immediate use of this:

  1. $sortableItems.find(settings.handleSelector).css({  
  2.     cursor: 'move'  
  3. }).mousedown(function (e) {  
  4.     $(this).parent().css({  
  5.         width: $(this).parent().width() + 'px'  
  6.     });  
  7. }).mouseup(function () {  
  8.     if(!$(this).parent().hasClass('dragging')) {  
  9.         $(this).parent().css({width:''});  
  10.     }  
  11. });  

So, we're looking for what has been defined as the 'handle' within the movable widgets (within sortableItems) and then we're applying a new CSS cursor property of 'move' to each one; this is to make it obvious that each widget is movable.

The mousedown and mouseup functions are needed to work around some issues with dragging and dropping... Since we want this page and all the elements inside it to expand when the browser is resized we haven't set any explicit widths on the widgets (list items). When one of these list items is being sorted it becomes absolutely positioned (while being dragged) which means that it will stretch to its content's composite width. Here's an example:

When dragged the widget stretches to length of page

This is what should be happening:

When dragged the widget has the correct width!

To make this happen we have explicitly set the widget's width to what it was before dragging had begun. The UI 'sortable' module does have a property in which you can put a function that will run when a widget starts being sorted (i.e. when it starts being dragged), unfortunately this is not good enough for us because it runs too late; we need to set the width before the 'sortable' module takes hold - the best way to do this is by running a function on mousedown of the handle (the 'handle', in this case, is the bar at the top of each widget).

  1. // mousedown function:  
  2. // Traverse to parent (the widget):  
  3. $(this).parent().css({  
  4.     // Explicitely set width as computed width:  
  5.     width: $(this).parent().width() + 'px'  
  6. });  

If we leave it like this then when you drop the widget in a certain place and res

the browser the widget will not change in size. In order to prevent this we need to write a function to be tied to the mouseup event of the handle:

  1. // mouseup function:  
  2. // Check if widget is currently in the process of dragging:  
  3. if(!$(this).parent().hasClass('dragging')) {  
  4.     // If it's not then reset width to '':  
  5.     $(this).parent().css({width:''}); 
  6. } else { 
  7.     // If it IS currently being dragged then we want to  
  8.     // temporarily disable dragging, while widget is 
  9.     // reverting to original position. 
  10.     $(settings.columns).sortable('disable');  
  11. }  

The 'dragging' class is added on that 'start' property of the sortable module which we talked about earlier. (we'll write that code later)

This is what our makeSortable method looks like so far:

  1. makeSortable : function () {  
  2.     var iNettuts = this,  
  3.         $ = this.jQuery,  
  4.         settings = this.settings,  
  5.           
  6.         $sortableItems = (function () {  
  7.             var notSortable = '';  
  8.             $(settings.widgetSelector,$(settings.columns)).each(function (i) {  
  9.                 if (!iNettuts.getWidgetSettings(this.id).movable) {  
  10.                     if(!this.id) {  
  11.                         this.id = 'widget-no-id-' + i;  
  12.                     }  
  13.                     notSortable += '#' + this.id + ',';  
  14.                 }  
  15.             });  
  16.             return $('> li:not(' + notSortable + ')', settings.columns);  
  17.         })();  
  18.       
  19.     $sortableItems.find(settings.handleSelector).css({  
  20.         cursor: 'move'  
  21.     }).mousedown(function (e) {  
  22.         $sortableItems.css({width:''});  
  23.         $(this).parent().css({  
  24.             width: $(this).parent().width() + 'px'  
  25.         });  
  26.     }).mouseup(function () {  
  27.         if(!$(this).parent().hasClass('dragging')) {  
  28.             $(this).parent().css({width:''});  
  29.         } else {  
  30.             $(settings.columns).sortable('disable');  
  31.         }  
  32.     });  
  33. }  

Next, still within 'makeSortable' we need to initialise the 'sortable' module:

  1. makeSortable : function () {  
  2.     // ...........................  
  3.     // BEGINNING OF METHOD (above)  
  4.     // ...........................  
  5.       
  6.     // Select the columns and initiate 'sortable':  
  7.     $(settings.columns).sortable({  
  8.       
  9.         // Specify those items which will be sortable:  
  10.         items: $sortableItems,  
  11.           
  12.         // Connect each column with every other column:  
  13.         connectWith: $(settings.columns),  
  14.           
  15.         // Set the handle to the top bar:  
  16.         handle: settings.handleSelector,  
  17.           
  18.         // Define class of placeholder (styled in inettuts.js.css)  
  19.         placeholder: 'widget-placeholder',  
  20.           
  21.         // Make sure placeholder size is retained:  
  22.         forcePlaceholderSize: true,  
  23.           
  24.         // Animated revent lasts how long?  
  25.         revert: 300,  
  26.           
  27.         // Delay before action:  
  28.         delay: 100,  
  29.           
  30.         // Opacity of 'helper' (the thing that's dragged):  
  31.         opacity: 0.8,  
  32.           
  33.         // Set constraint of dragging to the document's edge:  
  34.         containment: 'document',  
  35.           
  36.         // Function to be called when dragging starts:  
  37.         start: function (e,ui) {  
  38.             $(ui.helper).addClass('dragging');  
  39.         },  
  40.           
  41.         // Function to be called when dragging stops:  
  42.         stop: function (e,ui) {  
  43.           
  44.             // Reset width of units and remove dragging class:  
  45.             $(ui.item).css({width:''}).removeClass('dragging');  
  46.               
  47.             // Re-enable sorting (we disabled it on mouseup of the handle):  
  48.             $(settings.columns).sortable('enable');  
  49.               
  50.         }  
  51.           
  52.     });  
  53.       
  54. }  

The above options setup the behaviour we want for our sortable widgets. There are plenty more available options for this module but those above will be sufficient for now.

Editing, removing and collapsing widgets

The next step is to make it possible for the user to collapse widgets, close (remove) widgets and edit certain elements within each widget.

We're going to put this all within one method, we'll call it 'addWidgetControls':

  1. addWidgetControls : function () {  
  2.     // This function will add controls to each widget!  
  3. }  

As with 'makeSortable' we want to set the following variables at the start:

  1. addWidgetControls : function () {  
  2.     var iNettuts = this,  
  3.         $ = this.jQuery,  
  4.         settings = this.settings;  
  5. }  

We need to loop through every widget on the page and add functionality dependent on the default settings or the settings made for any particular widget.

  1. // Loop through each widget:  
  2. $(settings.widgetSelector, $(settings.columns)).each(function () {  
  3.   
  4.     /* Merge individual settings with default widget settings */  
  5.     var thisWidgetSettings = iNettuts.getWidgetSettings(this.id);  
  6.       
  7.     // (if "removable" option is TRUE):  
  8.     if (thisWidgetSettings.removable) {  
  9.       
  10.         // Add CLOSE (REMOVE) button & functionality  
  11.           
  12.     }  
  13.       
  14.     // (if "removable" option is TRUE):  
  15.     if (thisWidgetSettings.editable) {  
  16.       
  17.         // Add EDIT button and functionality  
  18.           
  19.     }  
  20.       
  21.     // (if "removable" option is TRUE):  
  22.     if (thisWidgetSettings.collapsible) {  
  23.       
  24.         // Add COLLAPSE button and functionality  
  25.           
  26.     }  
  27.           
  28. });  

As you can see from the above code, we're checking the settings before adding any one of the three buttons and each button’s corresponding functionality.

Before we write out exactly what will happen within each of three conditions let's list exactly what each of these buttons will do:

  • CLOSE (remove): This button will remove the widget from the DOM. Instead of just removing it immediately we'll apply an effect which will fade out he widget and then slide up its occupied space.
  • EDIT: This button, when clicked, will bring up an 'edit box' section within the widget. Within this 'edit' section the user can change the title of the widget and its colour. To close the 'edit' section the user must click on the same 'edit' button again - so basically this button toggles the 'edit' section.
  • COLLAPSE: This button switches between an up-arrow and a down-arrow dependent whether the widget is collapsed or not. Collapsing a widget will simply hide its content, so the only viewable of the widget will be the handle (the bar at the top of each widget).

We know what we want now, so we can start writing it: (The snippets below are riddles with comments so make sure you read through the code!)

CLOSE (remove):

  1. // (if "removable" option is TRUE):  
  2. if (thisWidgetSettings.removable) {  
  3.       
  4.     // Create new anchor element with class of 'remove':  
  5.     $('<a href="#" class="remove">CLOSE</a>').mousedown(function (e) {  
  6.       
  7.         // Stop event bubbling:  
  8.         e.stopPropagation();   
  9.              
  10.     }).click(function () {  
  11.       
  12.         // Confirm action - make sure that the user is sure:  
  13.         if(confirm('This widget will be removed, ok?')) {  
  14.           
  15.             // Animate widget to an opacity of 0:  
  16.             $(this).parents(settings.widgetSelector).animate({  
  17.                 opacity: 0      
  18.             },function () {  
  19.               
  20.                 // When animation (opacity) has finished:  
  21.                 // Wrap in DIV (explained below) and slide up:  
  22.                 $(this).wrap('<div/>').parent().slideUp(function () {  
  23.                   
  24.                     // When sliding up has finished, remove widget from DOM:  
  25.                     $(this).remove();  
  26.                       
  27.                 });  
  28.             });  
  29.         }  
  30.           
  31.         // Return false, prevent default action:  
  32.         return false;  
  33.           
  34.     })  
  35.       
  36.     // Now, append the new button to the widget handle:  
  37.     .appendTo($(settings.handleSelector, this));  
  38.       
  39. }  

EDIT:

  1. /* (if "editable" option is TRUE) */  
  2. if (thisWidgetSettings.editable) {  
  3.       
  4.     // Create new anchor element with class of 'edit':  
  5.     $('<a href="#" class="edit">EDIT</a>').mousedown(function (e) {  
  6.           
  7.         // Stop event bubbling  
  8.         e.stopPropagation();  
  9.           
  10.     }).toggle(function () {  
  11.         // Toggle: (1st state):  
  12.           
  13.         // Change background image so the button now reads 'close edit':  
  14.         $(this).css({backgroundPosition: '-66px 0', width: '55px'})  
  15.               
  16.             // Traverse to widget (list item):  
  17.             .parents(settings.widgetSelector)  
  18.                   
  19.                 // Find the edit-box, show it, then focus <input/>:  
  20.                 .find('.edit-box').show().find('input').focus();  
  21.                   
  22.         // Return false, prevent default action:  
  23.         return false;  
  24.           
  25.     },function () {  
  26.         // Toggle: (2nd state):  
  27.           
  28.         // Reset background and width (will default to CSS specified in StyleSheet):  
  29.         $(this).css({backgroundPosition: '', width: ''})  
  30.               
  31.             // Traverse to widget (list item):  
  32.             .parents(settings.widgetSelector)  
  33.                   
  34.                 // Find the edit-box and hide it:  
  35.                 .find('.edit-box').hide();  
  36.         // Return false, prevent default action:  
  37.         return false;  
  38.   
  39.     })  
  40.       
  41.     // Append this button to the widget handle:  
  42.     .appendTo($(settings.handleSelector,this));  
  43.       
  44.     // Add the actual editing section (edit-box):  
  45.     $('<div class="edit-box" style="display:none;"/>')  
  46.         .append('<ul><li class="item"><label>Change the title?</label><input value="' + $('h3',this).text() + '"/></li>')  
  47.         .append((function(){  
  48.               
  49.             // Compile list of available colours:  
  50.             var colorList = '<li class="item"><label>Available colors:</label><ul class="colors">';  
  51.               
  52.             // Loop through available colors - add a list item for each:  
  53.             $(thisWidgetSettings.colorClasses).each(function () {  
  54.                 colorList += '<li class="' + this + '"/>';  
  55.             });  
  56.               
  57.             // Return (to append function) the entire colour list:  
  58.             return colorList + '</ul>';  
  59.               
  60.         })())  
  61.           
  62.         // Finish off list:  
  63.         .append('</ul>')  
  64.           
  65.         // Insert the edit-box below the widget handle:  
  66.         .insertAfter($(settings.handleSelector,this));  
  67.           
  68. }  

COLLAPSE:

  1. // (if 'collapsible' option is TRUE)   
  2. if (thisWidgetSettings.collapsible) {  
  3.       
  4.     // Create new anchor with a class of 'collapse':  
  5.     $('<a href="#" class="collapse">COLLAPSE</a>').mousedown(function (e) {  
  6.           
  7.         // Stop event bubbling:  
  8.         e.stopPropagation();  
  9.           
  10.   
  11.     }).toggle(function () {  
  12.         // Toggle: (1st State):  
  13.           
  14.         // Change background (up-arrow to down-arrow):  
  15.         $(this).css({backgroundPosition: '-38px 0'})  
  16.           
  17.             // Traverse to widget (list item):  
  18.             .parents(settings.widgetSelector)  
  19.                 // Find content within widget and HIDE it:  
  20.                 .find(settings.contentSelector).hide();  
  21.                   
  22.         // Return false, prevent default action:  
  23.         return false;  
  24.           
  25.     },function () {  
  26.         // Toggle: (2nd State):  
  27.           
  28.         // Change background (up-arrow to down-arrow):  
  29.         $(this).css({backgroundPosition: ''})  
  30.           
  31.             // Traverse to widget (list item):  
  32.             .parents(settings.widgetSelector)  
  33.               
  34.                 // Find content within widget and SHOW it:  
  35.                 .find(settings.contentSelector).show();  
  36.                   
  37.         // Return false, prevent default action:  
  38.         return false;  
  39.           
  40.     })  
  41.       
  42.     // Prepend that 'collapse' button to the widget's handle:  
  43.     .prependTo($(settings.handleSelector,this));  
  44. }  

What is "Event Bubbling"?

Event bubbling or 'propagation' is when, upon clicking on an element, the event will bubble up through the DOM to the highest level element with an event the same as the event you just triggered on the original element. If we didn't stop propogation in the above snippets (e.stopPropagation();) on the mouseDown event of each added button then the mouseDown event of the handle (parent of the buttons) would also trigger and thus the dragging would would begin just by holding your mouse down over one of the buttons - we don't want this to happen; we only want dragging to begin when the user puts their mouse directly over the handle and pushes down.

Edit-box events/functionality

We've written the code which will inject the edit boxes into the document in the correct places. - We added an input box so users can change the title of a widget and we also added a list of available colours. So, we now need to loop through each new edit-box (hidden from view) and specify how these elements can be interacted with:

  1. // Loop through each edit-box (under each widget that has an edit-box)  
  2. $('.edit-box').each(function () {  
  3.       
  4.     // Assign a function to the onKeyUp event of the input:  
  5.     $('input',this).keyup(function () {  
  6.           
  7.         // Traverse UP to widget and find the title, set text to  
  8.         // the input element's value - if the value is longer  
  9.         // than 20 characters then replace remainder characters  
  10.         // with an elipsis (...).  
  11.         $(this).parents(settings.widgetSelector).find('h3').text( $(this).val().length>20 ? $(this).val().substr(0,20)+'...' : $(this).val() ); 
  12.          
  13.     }); 
  14.      
  15.     // Assing a function to the Click event of each colour list-item: 
  16.     $('ul.colors li',this).click(function () { 
  17.          
  18.         // Define colorStylePattern to match a class with prefix 'color-': 
  19.         var colorStylePattern = /\bcolor-[\w]{1,}\b/, 
  20.              
  21.             // Define thisWidgetColorClass as the colour class of the widget: 
  22.             thisWidgetColorClass = $(this).parents(settings.widgetSelector).attr('class').match(colorStylePattern) 
  23.         // If a class matching the pattern does exist: 
  24.         if (thisWidgetColorClass) { 
  25.              
  26.             // Traverse to widget: 
  27.             $(this).parents(settings.widgetSelector) 
  28.              
  29.                 // Remove the old colour class: 
  30.                 .removeClass(thisWidgetColorClass[0]) 
  31.                  
  32.                 // Add new colour class (n.b. 'this' refers to clicked list item): 
  33.                 .addClass($(this).attr('class').match(colorStylePattern)[0]);  
  34.                   
  35.         }  
  36.           
  37.         // Return false, prevent default action:  
  38.         return false;  
  39.           
  40.     });  
  41. });  

The edit-boxes are entirely functional now. All the above code resides in the 'addWidgetControls' method.

  1. addWidgetControls : function () {  
  2.     var iNettuts = this,  
  3.         $ = this.jQuery,  
  4.         settings = this.settings;  
  5.           
  6.     $(settings.widgetSelector, $(settings.columns)).each(function () {  
  7.         var thisWidgetSettings = iNettuts.getWidgetSettings(this.id);  
  8.           
  9.         if (thisWidgetSettings.removable) {  
  10.             $('<a href="#" class="remove">CLOSE</a>').mousedown(function (e) {  
  11.                 e.stopPropagation();      
  12.             }).click(function () {  
  13.                 if(confirm('This widget will be removed, ok?')) {  
  14.                     $(this).parents(settings.widgetSelector).animate({  
  15.                         opacity: 0      
  16.                     },function () {  
  17.                         $(this).wrap('<div/>').parent().slideUp(function () {  
  18.                             $(this).remove();  
  19.                         });  
  20.                     });  
  21.                 }  
  22.                 return false;  
  23.             }).appendTo($(settings.handleSelector, this));  
  24.         }  
  25.           
  26.         if (thisWidgetSettings.editable) {  
  27.             $('<a href="#" class="edit">EDIT</a>').mousedown(function (e) {  
  28.                 e.stopPropagation();      
  29.             }).toggle(function () {  
  30.                 $(this).css({backgroundPosition: '-66px 0', width: '55px'})  
  31.                     .parents(settings.widgetSelector)  
  32.                         .find('.edit-box').show().find('input').focus();  
  33.                 return false;  
  34.             },function () {  
  35.                 $(this).css({backgroundPosition: '', width: ''})  
  36.                     .parents(settings.widgetSelector)  
  37.                         .find('.edit-box').hide();  
  38.                 return false;  
  39.             }).appendTo($(settings.handleSelector,this));  
  40.             $('<div class="edit-box" style="display:none;"/>')  
  41.                 .append('<ul><li class="item"><label>Change the title?</label><input value="' + $('h3',this).text() + '"/></li>')  
  42.                 .append((function(){  
  43.                     var colorList = '<li class="item"><label>Available colors:</label><ul class="colors">';  
  44.                     $(thisWidgetSettings.colorClasses).each(function () {  
  45.                         colorList += '<li class="' + this + '"/>';  
  46.                     });  
  47.                     return colorList + '</ul>';  
  48.                 })())  
  49.                 .append('</ul>')  
  50.                 .insertAfter($(settings.handleSelector,this));  
  51.         }  
  52.           
  53.         if (thisWidgetSettings.collapsible) {  
  54.             $('<a href="#" class="collapse">COLLAPSE</a>').mousedown(function (e) {  
  55.                 e.stopPropagation();      
  56.             }).toggle(function () {  
  57.                 $(this).css({backgroundPosition: '-38px 0'})  
  58.                     .parents(settings.widgetSelector)  
  59.                         .find(settings.contentSelector).hide();  
  60.                 return false;  
  61.             },function () {  
  62.                 $(this).css({backgroundPosition: ''})  
  63.                     .parents(settings.widgetSelector)  
  64.                         .find(settings.contentSelector).show();  
  65.                 return false;  
  66.             }).prependTo($(settings.handleSelector,this));  
  67.         }  
  68.     });  
  69.       
  70.     $('.edit-box').each(function () {  
  71.         $('input',this).keyup(function () {  
  72.             $(this).parents(settings.widgetSelector).find('h3').text( $(this).val().length>20 ? $(this).val().substr(0,20)+'...' : $(this).val() );  
  73.         });  
  74.         $('ul.colors li',this).click(function () {  
  75.               
  76.             var colorStylePattern = /\bcolor-[\w]{1,}\b/,  
  77.                 thisWidgetColorClass = $(this).parents(settings.widgetSelector).attr('class').match(colorStylePattern)  
  78.             if (thisWidgetColorClass) {  
  79.                 $(this).parents(settings.widgetSelector)  
  80.                     .removeClass(thisWidgetColorClass[0])  
  81.                     .addClass($(this).attr('class').match(colorStylePattern)[0]);  
  82.             }  
  83.             return false;  
  84.               
  85.         });  
  86.     });  
  87.       
  88. }  

Almost finished

Now that we've written most of the JavaScript we can write the initiating method and intialise the script!

  1. // Additional method within 'iNettuts' object:  
  2. init : function () {  
  3.     this.attachStylesheet('inettuts.js.css');  
  4.     this.addWidgetControls();  
  5.     this.makeSortable();  
  6. }  

Now, to start it all:

  1. // Right at the very end of inettuts.js  
  2. iNettuts.init();  

Just so we're clear, this is the overall structure of our iNettuts object with each of its methods explained:

  1. var iNettuts = {  
  2.       
  3.     /* Set's jQuery identifier: */  
  4.     jQuery : $,  
  5.       
  6.     settings : {  
  7.           
  8.         /*    Name : settings 
  9.          *    Type : Object 
  10.          * Purpose : Object to store preferences for widget behaviour 
  11.          */  
  12.            
  13.     },  
  14.   
  15.     init : function () {  
  16.           
  17.         /*    Name : init 
  18.          *    Type : Function 
  19.          * Purpose : Initialise methods to be run when page has loaded. 
  20.          */  
  21.            
  22.     },  
  23.       
  24.     getWidgetSettings : function (id) {  
  25.           
  26.         /*      Name : getWidgetSettings 
  27.          *      Type : Function 
  28.          * Parameter : id of widget 
  29.          *   Purpose : Get default and per-widget settings specified in  
  30.          *             the settings object and return a new object 
  31.          *             combining the two, giving per-widget settings 
  32.          *             precedence obviously. 
  33.          */  
  34.            
  35.     },  
  36.       
  37.     addWidgetControls : function () {  
  38.           
  39.         /*    Name : settings 
  40.          *    Type : Function 
  41.          * Purpose : Adds controls (e.g. 'X' close button) to each widget. 
  42.          */  
  43.            
  44.     },  
  45.       
  46.     attachStylesheet : function (href) {  
  47.           
  48.         /*      Name : settings 
  49.          *      Type : Function 
  50.          * Parameter : href location of stylesheet to be added 
  51.          *   Purpose : Creates new link element with specified href and  
  52.          *             appends to <head> 
  53.          */  
  54.            
  55.     },  
  56.       
  57.     makeSortable : function () {  
  58.           
  59.         /*    Name : settings 
  60.          *    Type : Function 
  61.          * Purpose : Makes widgets sortable (draggable/droppable) using 
  62.          *           the jQuery UI 'sortable' module. 
  63.          */  
  64.            
  65.     }  
  66.     
  67. };  

 Finished!

Finished Project

We're totally finished, the interface should be totally operable now. I've tested it on my PC (running Windows XP) in the following browsers: Firefox 2, Firefox 3, Opera 9.5, Safari 3, IE6, IE7 & Chrome.

Note: There are a couple of issues in IE. Specifically, it doesn't set the placeholder size correctly plus there are some CSS issues in IE6 (to be expected).

At first glance this interface's potential applications seem limited to those like iGoogle or NetVibes but it can, in fact, be used for many different things.

  • You could, for example use it on your blog by giving the user the option to sort your blog's widgets in the sidebar - you could then save their preference to a cookie so that the widgets would be in the same order when the user returns.
  • If you add a user authentication system and a database then you've got yourself a simple iGoogle.
  • The 'sortable' plugin itself can be used for sorting any elements, they don't have to be widgets.

Regardless of whether you're going to use this in a project or not I hope you've learnt something today!


by Anna 안나 2009. 3. 1. 00:20
http://net.tutsplus.com/articles/web-roundups/the-20-most-practical-and-creative-uses-of-jquery/

There have been plenty of posts on the number of awesome jQuery plugins and where to find them. However, sometimes it is best not to rely on third party plugins and resources. Do it yourself the old fashioned way! Today, we will have a look at 20+ creative uses of jQuery in modern day websites and applications; sure to inspire you for your next project.

Author: Drew Douglass

Hi, I'm Drew and I am a freelance developer and designer. I love all things having to do with PHP, MySQL, CSS, or jQuery. You can find my weekly articles on the ThemeForest blog and at Dev-Tips.com. Feel free to follow me if you're a fellow twitter addict.

  • James Padolsey Color Switcher

    Screenshot 1

    One of our sporadic writers, James Padolsey, has a nice feature on his website. A "customize" bar in the top right portion of the screen allows you to change the background color of the header.

    Visit Site

  • Dragon Interactives jQuery Navigation

    Screenshot 1

    These guys are pretty much Gods of web design, and their site really proves it. Just have a look at the custom jQuery navigation they used on their homepage. Have you ever seen such a sexy navigation in your life?

    Visit Site

  • FamSpams FaceBox

    Screenshot 2

    FamFamFam needed a custom lightbox like script for FamSpam (whew, say that three times). They ended up building what is now know as FaceBox, which replicates the effects of lightbox, but goes above and beyond by allowing you to load in static html pages, contact forms, anything you wish really! FaceBox is now a jQuery plugin after all the demand for their script.

    Visit Site

  • Grooveshark Widget Creator

    Screenshot 3

    Instead of going with a typical flash menu/control menu, Grooveshark mixed it up a bit and built a custom jQuery script to allow you to make your own music widgets; pretty nifty indeed.

    Visit Site

  • CSS-Tricks Fade-In Navigation

    Screenshot 4

    CSS-Tricks, by Chris Coyier, is next up on the list with a wonderfully simple and creative jQuery navigation. When the links are hovered over, instead of immediately changing colors, jQuery is used to help the color fade slowly to the desired color.

    Visit Site

  • David Walsh Link Nudge

    Screenshot 5

    Developer David Walsh of DavidWalsh.name implements an extremely simple to use script to give your links a little nudge on hover. The script utilizes the strong animation capabilities of jQuery triggered on hover. Check out the links in the sidebar and in the footer to see the effect in action.

    Visit Site

  • CarrotCreative-Custom Sites Lightbox

    Screenshot 6

    If you check out the CarrotCreative website, you will actually notice two really unique jQuery effects. Firstly, if you click on sites in the upper left, you will see a unique application of a 'lightbox' like effect listing their sites and icons. Secondly, if you click on any navigation links, you will notice there is no refresh, but that the new page just slides in from the right. Cool stuff!

    Visit Site

  • BrightCreative Portfolio

    Screenshot 7

    Another "two for one" special, Bright Creative uses an extremely subtle glow effect in their navigation that is very calming and warm. In addition, all of their portfolio pages have a tabbing effect, so their is no need for the user to refresh the page every time - thanks to AJAX and jQuery.

    Visit Site

  • Incredible Login Form

    Screenshot 1

    Not too long ago, Connor Zwick wrote us a nice tutorial that demonstrates exactly how to build an amazing drop-down login form.

    Visit Site

  • Application Scroller by Aviary

    Screenshot 8

    It would be an insult to call this a type of 'marquee' (shivers uttering that word). Instead, Aviary came up with a very nice looking and functioning 'scroller' to showcase a lot of text in a small amount of space. Even better is that the scroller will degrade gracefully is javascript is disabled.

    Visit Site

  • Featured Fade Effect by DesignFlavr

    Screenshot 9

    DesignFlavr, known for their great sources of design inspiration, put together a simple fadeIn/fadeOut script to showcase their featured artwork and corresponding descriptions. Also, they've used the lavalamp plugin quite well on their main navigation.

    Visit Site

  • Hv-Designs Fade In RSS Icon

    Screenshot 11

    On the Hv-Designs homepage, you will notice the the RSS icon starts off as an outline/sketch of the actual image. Then, when hovered, the rss icons 'glows' into place.

    Visit Site

  • Asylums Custom Scroller

    Screenshot 12

    Besides being an absolutely hilarious website, Asylum has their own sweet 'featured articles' scrolling script. It's hard to put a finger on why this one is so nice, but that is probably because it behaves slightly differently than most scrolling scripts. It almost seems to snap into place after you give it a click.

    Visit Site

  • 5 Javascript Tricks Made Easy with jQuery

    Screenshot 14

    Brian Reindel created a webpage showcasing 5 custom scripts you can use however you like. The article takes ideas and previous javascript techniques frequently used and utilizes jQuery to make them powerful, compact, and easy to read.

    Visit Site

  • Codas Entire Website

    Screenshot 15

    Coda is well known for its amazing UI and site design. It set a fire under the jQuery plugin community by inspiring many developers to re create their page tabbing effect. In addition, they have a wonderful on hover effect on the links located in the header.

    Visit Site

  • Clark Lab Fading Effect

    Screenshot 16

    ClarkLab is a well known and very successful author on ThemeForest. If you visit his portfolio below, you will notice the large header images eventually fade to the next, showcasing all of his latest work. The fade effect is so well done and subtle, you barely notice the new image showing up.

    Visit Site

  • Rob Young | E is for Effort

    Screenshot 17

    Designer and Art Director Rob Young used a unique idea of displaying his artwork on a simulated Mac screen. Then using jQuery scrolling effects, each new page slides into the page view as if it is being loaded on a computer.

    Visit Site

  • Web Designer Wall

    Screenshot 18

    Besides being a visually stunning website, WDW features some unique custom jQuery scripting to add classes to certain elements on hover. Check out the effects when the rss and navigation items are hovered over.

    Visit Site

  • Junaid W. Hanif

    Screenshot 19

    Another really cool tabbing effect - instead of arrows however, pagination and AJAX is used to create a sleek and clean user experience. Plus, the navigation has a very nice albeit simple effect.

    Visit Site

  • KomodoMedia

    Screenshot 19

    I've saved my absolute favorite site for last. First, just look at that design, it's wonderfully unique and comforting. Using one of the most creative jQuery scripts I have ever seen, KM has a 'foliage-o-meter' slider where sliding it either increases or decreases the foliage and design of the theme, depending on the direction the slider is moved. For an easter egg be sure to check out the source code!

    Visit Site

Keep in mind that jQuery is simply a tool and is only limited by your creativity and skill level. Get unique with your designs and development process and you might be surprised to see great results occur. Please be sure to share any of your favorite websites featuring unique uses of jQuery in the comments section below! ...And a Digg or Stumble would be greatly appreciated! :)

  • Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.

by Anna 안나 2009. 2. 27. 18:42
http://newism.com.au/blog/post/58/bigtarget-js-increasing-the-size-of-clickable-targets/

Say goodbye to boring ‘Read More…’ links by turning your entire content block into a clickable target!

With all the positive focus on grid based web design these days, I started to identify a couple of standard design elements. The main pattern used in nearly every site (grid and non grid) was the “title, thumbnail, short summary, more link” pattern. This pattern is generally used for indexing blog post summaries in sidebars, listing services, or creating small calls-to-action.

The XHTML markup generally looks something like this:

<div>
<h3><a href="http://leevigraham.com/">Title</a></h3>
<a href="http://leevigraham.com/"><img src="thumbnail.png" alt="thumbnail" /></a>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
<a href="http://leevigraham.com/">Read More …</a>
</p>
</div>

One thing that always bugged me when implementing the code above, wasn’t necessarily the number of links inside a small block of content, it was the fact that only those small bits of sporadic content were clickable. Sure it’s not that hard for the user to hover over one of the three links, but I thought the user experience could be improved.

My feeling was that a user should be able to click anywhere in the content and navigate through to the target page — basically making the whole content block one big link.

Improving usability and the user experience with jQuery

Wrapping a single anchor around the whole content (title, thumbnail, summary) is a bad idea as it’s not standards compliant and renders the page invalid. So I turned to my good friend jQuery and threw together the following plugin using the ‘Learning jQuery’ plugin development pattern.

The concept is simple:

  1. Attach the plugin to any link in the content block.
  2. Pass through the click zone selector as a plugin option.
  3. The plugin then attaches onclick and hover events to the click zone.
  4. User clicks anywhere on the click zone.
  5. The original link href is retrieved.
  6. If the link has a rel attribute and it’s set to ‘external’, open the link target in a new window; otherwise open the link in the current browser window.

A working example

A list of entries without bigTarget.js applied

  1. Example Title 1

    thumbnail

    Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Morbi tempor posuere libero. In fringilla magna ut urna elementum condimentum. Aliquam erat volutpat. Fusce odio. Read More …

  2. Example Title 2

    thumbnail

    Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Morbi tempor posuere libero. In fringilla magna ut urna elementum condimentum. Aliquam erat volutpat. Fusce odio. Read More …

  3. Example Title 3

    thumbnail

    Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Morbi tempor posuere libero. In fringilla magna ut urna elementum condimentum. Aliquam erat volutpat. Fusce odio. Read More …

A list of articles with bigTarget.js applied

  1. Example Title 1

    thumbnail

    Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Morbi tempor posuere libero. In fringilla magna ut urna elementum condimentum. Aliquam erat volutpat. Fusce odio. Read More …

  2. Example Title 2

    thumbnail

    Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Morbi tempor posuere libero. In fringilla magna ut urna elementum condimentum. Aliquam erat volutpat. Fusce odio. Read More …

  3. Example Title

    thumbnail

    Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Morbi tempor posuere libero. In fringilla magna ut urna elementum condimentum. Aliquam erat volutpat. Fusce odio. Read More …

bigTarget.js

Now you know what bigTarget.js does, you’ll probably want to grab the code and start using it on your site.

Usage

Adding bigTarget.js functionality to your site is straight forward. First include the plugin code in the head of your document, and then when the page is ready, attach the bigTarget function to the target anchor — bigTarget.js will do the rest.

$(document).ready(function(){
$("ol.bigTarget h4 a").bigTarget();
});

Customising the hoverClass and clickZone

There are two options to further customise how bigTarget.js works — clickZone and hoverClass. By default, bigTarget.js will turn the first parent <li> tag of the target anchor into the click zone using li:eq(0) as the parent selector. The plugin will also add the class ‘hover’ to the click zone element.

This is fine for cases when your content is a series of ordered or unordered list elements. However you may prefer to use a series of <div> tags as the click zone elements and apply the class ‘over’ when the user hovers over the element. To do this just pass the options to the function like so:

$(document).ready(function(){
$("ol.bigTarget h4 a").bigTarget({
hoverClass: 'over', // CSS class applied to the click zone onHover
clickZone : 'div:eq(0)' // jQuery parent selector
});
});

The code

The plugin code for bigTarget.js is short and sweet.

Paste the code below into a new file called jquery.bigtarget.1.0.1.js or download it from here, then add a <script src="jquery.bigTarget.js.1.0.0" type="text/javascript"></script> to the <head> of your document before calling the bigTarget() method on the selected elements.

// bigTarget.js - A jQuery Plugin
// Version 1.0.1
// Written by Leevi Graham - Technical Director - Newism Web Design & Development
// http://newism.com.au
// Notes: Tooltip code from fitted.js - http://www.trovster.com/lab/plugins/fitted/

// create closure
(function($) {
// plugin definition
$.fn.bigTarget = function(options) {
debug(this);
// build main options before element iteration
var opts = $.extend({}, $.fn.bigTarget.defaults, options);
// iterate and reformat each matched element
return this.each(function() {
// set the anchor attributes
var $a = $(this);
var href = $a.attr('href');
var title = $a.attr('title');
// build element specific options
var o = $.meta ? $.extend({}, opts, $a.data()) : opts;
// update element styles
$a.parents(o.clickZone)
.hover(function() {
$h = $(this);
$h.addClass(o.hoverClass);
if(typeof o.title != 'undefined' && o.title === true && title != '') {
$h.attr('title',title);
}
}, function() {

$h.removeClass(o.hoverClass);
if(typeof o.title != 'undefined' && o.title === true && title != '') {
$h.removeAttr('title');
}
})
// click
.click(function() {
if(getSelectedText() == "")
{
if($a.is('[rel*=external]')){
window.open(href);
return false;
}
else {
//$a.click(); $a.trigger('click');
window.location = href;
}
}
});
});
};
// private function for debugging
function debug($obj) {
if (window.console && window.console.log)
window.console.log('bigTarget selection count: ' + $obj.size());
};
// get selected text
function getSelectedText(){
if(window.getSelection){
return window.getSelection().toString();
}
else if(document.getSelection){
return document.getSelection();
}
else if(document.selection){
return document.selection.createRange().text;
}
};
// plugin defaults
$.fn.bigTarget.defaults = {
hoverClass : 'hover',
clickZone : 'li:eq(0)',
title : true
};
// end of closure


1/1/08 8:51am — I have updated some of the plugin code for legibility and added a tooltip based on the work of Trevor Morris.

1/1/08 8:51am — My good friend Trovster (Trevor Morris) has independently published fitted.js which achieves the same goals as bigTarget.js in a slightly different manner.


})(jQuery);

Go forth and embiggen

bigTarget.js is a simple to use jQuery plugin that will give your visitors a better online experience. If you have any questions or feedback about bigTarget.js leave them in the comments below. If you find it useful, spread the bigTarget.js love through your preferred social network below.


by Anna 안나 2009. 2. 23. 17:31
http://nameslayer.tistory.com/tag/jquery

최근에 개발을 하면서 jQuery를 사용하기 시작했다. prototype보다 기본으로 제공되는 UI도
괜찮아보여 사용하기 시작하였는데, 역시 쉽지만은 않았다. ㅠㅠ
나도 어여 괜찮은 플러그인들을 개발할 수 있도록 노력중이지만, 언제쯤이나 가능할련지..

이하 펌...
==============================================================

알려진 JavaScript Framework(Library) 중 최근 가장 주목을 받고 있는 것중의 하나가 jQuery로 흥미롭게 살펴보고 있다.  
이전 포스트의 내용과 새로운 내용을 포함하여 정리한다.




* 주요 플러그인

01) Lightbox 류
 -
warren.mesozen.com/jquery-lightbox/
 - ThickBox 3.1  jquery.com/demo/thickbox/  [IE7, position bug]
 -
jQuery Lightbox Plugin
 - Facebox  famspam.com/facebox
 - FancyBox  fancy.klade.lv
 -
Simple Modal 
 - jqModal 
 -
prettyPhoto
 - Suckerfish HoverLightbox
 - piroBox 

02) Menu & Navigation
-
Elastic Menu : like mootools sliding effect
-
Step Menu
-
Navigation : LavaLamp
- Tree-View Menu
- jQuery File Tree
- jQuery UI Tabs
-
Tabbed Content [demo]
- Create A Tabbed Interface Using jQuery
-
Keypress Navigation Using jQuery
- Sliding Top Menu With jQuery
- Sprite + jQuery Navigation  Background Image Animation
- Sliding Menu
- Apple style Menu
- Garage Door Style Menu

03) Sliding & Scroll & Tickter 류
- ez=jQuery (Easy Slide, Easy News, Easy News Plus, Easy POP Show
- liScroll (a jQuery News Ticker made easy)
- InnerFade with jQuery

04) Message Alert 류
-
Dialog
-
Floating Windows
-
Tooltips  simple tooltip
- jGrowl (notice)
- Top Floating Message box using jQuery

05) Date Picker (Calendar)
-
Calendar(date-picker)
- Date Range Picker

06) Color Picker
-
Color Picker 
-
eyecon.ro/colorpicker/

07) Charts 류
-
Flot, jQuery plotting plug-in
- charts using canvas 
-
jQchart
- jQuery.sparkline

08) Accordion
-
Accordion
- dynamicDrive version accordion
- from Roshanbh.com - Blog
- accordion, a simple horizontal accordion plugin for jQuery

09) Forms
- Form
-
Nice Form 
-
Form Input Plugin 
-
Flexible and Semantic Forms
- Submit A Form Without Page Refresh using jQuery
- autotab
- Using Ajax to Validate Forms
- Auto-populating Select Boxes using jQuery & Ajax
- jQuery tutorial: Text box hints
- Forms, Context highlighting

10) Image
-
imgAreaSelect (crop)
- Jcrop (이미지 crop)
-
jQZoom
- jQuery Cycle plugin
- Fix the missing PNG-transparency in IE5.5, IE6
- Image Show(ImageFlow)
- SpaceGallery
- jquery-exif-data-plugin
- jParallax - view layered image
- SliderViewer
- Galleriffic
- dwImageProtector Plugin for jQuery

11) Table
-
tableSorter
- Zebra-Stripe Tables
- jQuery Table Striping Bug

12) Utility
- Dimension
- Interface
-
getUrlParam
- jQuery.Hotkeys.Testing
- Parsing Strings with jQuery
- addSizes.js: Sanzzy automatic link file-size generation
- Creating a Virtual jQuery Keyboard
- Cookie

13) Effect
- Flip

14)
jRails (jQuery on Rails)

15) Extensible CSS interface 2: CSS Selectors & jQuery

16) In-Place Editor

17) Virtual Tour

18) Simple Star Rating System

19) jQuery Corner

20) Feature your products with jQuery


[참고]
-
jQuery Ideas and Resources
- jQuery for Designers , jQuery Tutorials for Designers
- 51+ Best of jQuery Tutorials and Examples
- 50+ Amazing jQuery Examples - part1
- 37 More Shocking jQuery Plugins
- 45+ Fresh Out of the oven jQuery Plugins
- 65 Excellent jQuery Resources
- 8 Fantastic jQuery Tutorials for Designers
- Useful jQuery: A Compilation of jQuery Utilities
- CSS Developer - Why Aren't You Using jQuery?
- Absolute Positioning Using JQuery
- 20 jQuery Plugins for Unforgettable User Experience
- jQuery Robot
by Anna 안나 2009. 2. 23. 17:31
에 배틀제이 님이 올려주신 예제로 소개해 드리겠습니다.
의외로 쉽고 활용도가 높습니다.

<script language="JavaScript">

function getHttprequest(URL) {
// 기본적인 변수 선언
var xmlhttp = null;
// FF일 경우 window.XMLHttpRequest 객체가 존재한다.
if(window.XMLHttpRequest) {
// FF 로 객체선언
xmlhttp = new XMLHttpRequest();
} else {
// IE 경우 객체선언
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

// GET 모드로 URL 주소의 값을 가져온다
// 주의 해야 할점은 무조건 UTF 로 값이 들어옴
xmlhttp.open('GET', URL,false);

// 값을 가져 왔을경우 호출할 메소드를 바로 선언
xmlhttp.onreadystatechange = function() {

// readyState 가 4 고 status 가 200 일 경우 올바르게 가져옴
if(xmlhttp.readyState==4 && xmlhttp.status == 200 && xmlhttp.statusText=='OK') {
// responseText 에 값을 저장
responseText = xmlhttp.responseText;
}
}
xmlhttp.send('');

// 가져온 xmlhttp 객체의 responseText 값을 반환
return responseText = xmlhttp.responseText;
}



function replace(URL) {
document.getElementById('replace_area').innerHTML = getHttprequest(URL);
}

</script>

<div id='replace_area'> 냐하하~~ </div>

<a href = 'javascript:replace('test.php?bo_table=<?=bo_table?>&wr_id=<?=$wr_id?>');'> 가져오기 </a>


위 소스는 '가져오기' 를 클릭시 'test.php' 를 통해 출력되는 결과를 innerHTML 로
<div id='replace_area'></div> 속에 넣게 됩니다. '냐하하' 는 사라 지겠죠.

이때 화면의 리로드는 일어 나지 않으면서 출력 화면을 변화 시킬 수 있습니다.
즉 필요한 데이터만 가져다가 화면에 뿌려 줄 수 있다는 점이 장점입니다.

기존에 팝업창으로 해결해야 했던 부분들을 이러한 방법으로 화면내에 처리 할 수 있고,
실시간으로 테이터를 리플레쉬 할 수 도 있는 등 써 먹을때가 무척 많습니다.

단 주의하실 점은 XMLHttpRequest 로 받아 오는 데이터가 UTF-8 로 출력되기에 본인의 환경에 맞게
iconv 등을 통해서 EUC-KR 등으로 변환하는 과정이 필요합니다.


ob_start();
줄줄이 내용~~~~~~
$data = ob_get_contents();
ob_end_clean();
echo iconv("CP949", "UTF-8", $data);
요런게 한 방법이 되겠죠?
( 반대로 한글 변수를 전달 시에는 UTF-8 로 변환 전송 해야합니다. )

그리고 그냥 innerHTML 로 삽입시 가져온 문서에 스크립트가 있는 경우 작동을 안하는 경우가
있는데 <script DEFER language="JavaScript"> 식으로 DEFER 을 넣으면 되기도 하던데,
전문가가 아니라 잘 모르겠네요.

저 같이 프로그램 전문가가 아닌 분들을 위해 함 적어 봤습니다.
혹 오류 있으면 지적 부탁드리고요. ajax 란게 어려워 보여도 좋은 소스들이 많이 나와 있어서
그러한 소스들 적용하는 방법만 익히는 거라면 그리 어렵지는 않은 거 같습니다.
by Anna 안나 2009. 1. 12. 00:09

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
<script type="text/javascript">
var xhr;
function createRequest(){
if(window.ActiveXObject)
xhr = new ActiveXObject("Microsoft.XMLHTTP");
else if(window.XMLHttpRequest)
xhr = new XMLHttpRequest();
}

function test(){
createRequest(); // 함수호출로 사용자의 브라우저를 판단한 후 XMLHttprequest객체를 얻어내었다.
xhr.onreadystatechange = res; // 서버에서 응답이 전달될 때 그 응답을 받을 함수
var str = document.all.sel.value;
var param = "sel="+escape(encodeURIComponent(str));// 한글처
xhr.open("get", "innerHTMLEx2.jsp?"+param, true); // 요청방식과 요청할 페이지 비동기식 설정
xhr.send(null); // 서버요청 수행
}

function res(){
if(xhr.readyState == 4) // 서버 데이터 처리가 완료된 경우 : 4
if(xhr.status == 200){// 정상적인 완료 : 200
var str = xhr.responseText; // 응답 문자열
var tt = document.getElementById("tt");
tt.innerHTML = str;
}
}
</script>
</head>
<body>
과정 : <select id="sel">
<option value="과정1">과정1
<option value="과정2">과정2
</select><input type="button" value="보내기" onclick="test()">
<div id="tt" style="border:1 solid lightsteelblue;width:300px;height:100px;background:#dedede">
&nbsp;
</div>
</body>
</html> <%@page import="java.net.URLDecoder"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<%
String sel = URLDecoder.decode(
request.getParameter("sel"),"utf-8");
String code = "";
if(sel.equals("과정1"))
code = "JAVA, JSP, Ajax, Struts";
else if(sel.equals("과정2"))
code = "JAVA, XML, Flex, Struts";
else
code = "준비 중...";
%>
<%=code %>
by Anna 안나 2009. 1. 5. 13:31


<html>
<head><title>예제 9-5</title></head>
<body bgcolor="yellow"
onload="srcTxt.value=objDiv.outerHTML">
<h3>innerHTML, innerText, outerHTML, outerText 비교하는 예</h3>
<hr noshade>
<div id="objDiv" style="background-color:cyan">
<p>아래 링크와 버튼에서 액세스되는 <b>div</b> 객체입니다.
</div>
<p>
위의 div 태그는 다음과 같습니다 <br>
<textarea id="srcTxt" rows=5 cols=50>
</textarea>
<hr noshade>
다음 버튼을 클릭하면 위의 div 객체 내의 속성을 보여줍니다.<p>
<a href="javascript:alert(objDiv.innerHTML)">div의 innerHTML</a><br>
<a href="javascript:alert(objDiv.outerHTML)">div의 outerHTML</a><br>
<a href="javascript:alert(objDiv.innerText)">div의 innerText</a><br>
<a href="javascript:alert(objDiv.outerText)">div의 outerText</a><p>
<hr noshade>
아래 창에 입력하여 변경하면 위의 div 객체의
내용이 변하는 것을 확인할 수 있습니다.<p>
변경하고자 하는 innerText를 입력하세요.<br>
<input type="text" id="inText" value="테스트 innerText">
<button onClick="objDiv.innerText=inText.value;">변경</button><br>
변경하고자 하는 outerText를 입력하세요.<br>
<input type="text" id="outText" value="테스트 outerText">
<button onClick="objDiv.outerText=outText.value;">변경</button>
<!-- outerText 변경시 objDiv까지 주소값이 변경됨 -->
</body>
</html>
by Anna 안나 2009. 1. 5. 13:26
innerHTML은 매우 유용하지만 한계가 있습니다. var target = '<li id="swim" class="insertClass">수영</li><li id="soccer">축구</li>'; 이와 같이 작성한 것을 한번에 DOM 트리에 반영할 수 있는 것이 innerHTML입니다. 그런데 여기서 간과해서는 안되는 것이 innerHTML의 위치가 child Node라는 것입니다. 즉, 위치가 정해져 있다는 것입니다 만약, parent 노드의 앞과 뒤의 Sibiling Node 위치에 위의 HTML 스크립트(Fragment)를 반영하려면 어떻게 해야할까요? innerHTML만으로는 이를 처리할 수 없습니다. 따라서 DOM에서 제공하는 메소드를 사용해야 하며, 이 또한 IE와 다르므로 IE에서 제공하는 메소드를 사용해야 합니다 IE는 insertAdjacentHTML()로 처리할 수 있으며 DOM은 createRange(), setStartBefore()/setStartAfter(), createContextualFragment()로 처리할 수 있습니다. 소스 코드는 여러분이 만들어 보시기 바랍니다. 다음에 실행이 되는 소스 코드를 게재하겠습니다.
by Anna 안나 2009. 1. 5. 13:24
jQuery란 무엇인가? 2006 년 초, John Resig가 만든 jQuery는 JavaScript 코드로 작업하는 사람들에게는 훌륭한 라이브러리이다. 여러분이 JavaScript 언어 초보자라서 라이브러리가 Document Object Model (DOM) 스크립팅과 Ajax의 복잡성을 다루어주기를 원하든지, 숙련된 JavaScript 구루로서 DOM 스크립팅과 Ajax의 반복성에 지루해졌다면, jQuery가 제격이다. jQuery는 코드를 단순하고 간결하게 유지한다. 많은 반복 루프와 DOM 스크립팅 라이브러리 호출을 작성할 필요가 없다. jQuery를 사용하면 매우 적은 문자로 표현할 수 있다. jQuery 철학은 매우 독특하다. 무엇이든 단순하고 재사용 가능한 것으로 유지하기 위해 디자인 되었다. 여러분이 이러한 철학을 이해하고 여기에 편안함을 느낀다면, jQuery가 여러분의 프로그래밍 방식을 충분히 향상시킬 수 있다.
((-------IMAGE-------)) ((-------IMAGE-------))
((-------IMAGE-------))
위로

단순화 다 음은 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_links는 external_links의 id를 가진 엘리먼트를 찾는다. 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();

((-------IMAGE-------)) ((-------IMAGE-------))
((-------IMAGE-------))
위로

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'); }); }

((-------IMAGE-------)) ((-------IMAGE-------))
((-------IMAGE-------))
위로

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');

((-------IMAGE-------)) ((-------IMAGE-------))
((-------IMAGE-------))
위로

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) 문서를 참조하라. (참고자료)
((-------IMAGE-------)) ((-------IMAGE-------))
((-------IMAGE-------))
위로

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 셀렉터를 사용하여 이를 정의하는 방법도 찾을 수 있다.
((-------IMAGE-------)) ((-------IMAGE-------))
((-------IMAGE-------))
위로

플러그인으로 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 호출을 구현하는 상황에 사용된다.
((-------IMAGE-------)) ((-------IMAGE-------))
((-------IMAGE-------))
위로

jQuery 이후의 삶 jQuery 를 사용하여 할 수 있는 것의 표면적인 부분만 다루었다. jQuery는 기분 좋게 사용할 수 있고 새로운 트릭이나 기능도 자연스럽다. jQuery는 JavaScript와 Ajax 프로그래밍을 매우 단순화 시킬 수 있다. 새로운 것을 배울 때마다 코드는 더욱 단순해 진다. jQuery를 배운 후에, 필자는 JavaScript 언어로 하는 프로그래밍에 재미를 발견했다. 지루한 부분은 알아서 처리되기 때문에, 필자는 중요한 코딩 부분에만 집중하면 된다. jQuery를 사용하게 되면서 지난날 for 루프를 작성하던 때는 거의 기억이 나지 않는다. 심지어, 다른 JavaScript 라이브러리를 사용할 생각도 거의 하지 않는다. jQuery는 JavaScript 프로그래밍 방식을 진정으로 바꿔 놓았다.

참고자료교육
한국 developerWorks XML 존: 한국 developerWorks XML 존에서 XML 관련 자료를 더 볼 수 있다.

jQuery API 문서

jQuery 튜토리얼

Visual jQuery: jQuery API 레퍼런스.

IBM XML 인증: XML 분야의 IBM 인증 개발자에 도전하십시오.

XML 기술 자료: 한국 developerWorks XML 존에서 다양한 기술 자료, 팁, 튜토리얼, 표준, IBM Redbook 참고하기.


제품 및 기술 얻기
jQuery: jQuery 메인 사이트를 방문해 소프코드 다운로드 하기.

Selectors: CSS3과 XPath 셀렉터를 포함하여 jQuery에 사용되는 모든 셀렉터들.

jQuery 플러그인

Interface

Form 플러그인


토론
jQuery 블로그: : 공식 jQuery 블로그에서 정규 뉴스와 업데이트 확인하기.

XML 존 토론 포럼
by Anna 안나 2009. 1. 5. 13:22
iframe을 부득이하게 사용하는 웹페이지를 만들다보면 iframe의 크기를 자꾸 바꿔줘야 하는 경우가 왕왕 발생한다.
다음의 예제는 iframe의 크기를 자동으로 바꿔주는 예제이다.

kurapa.com에도 적용해 보았는데, 잘 동작하는 것을 확인하였다.

<iframe id='ifrm'
frameborder=0
width=100%
height=450
scrolling=no
src='http://kurapa.com'
></iframe>

<script language='javascript'>

function getDocHeight(doc)
{
var docHt = 0, sh, oh;
if (doc.height)
{
docHt = doc.height;
}
else if (doc.body)
{
if (doc.body.scrollHeight) docHt = sh = doc.body.scrollHeight;
if (doc.body.offsetHeight) docHt = oh = doc.body.offsetHeight;
if (sh && oh) docHt = Math.max(sh, oh);
}
return docHt;
} function getReSize()
{
var iframeWin = window.frames['ifrm']; var iframeEl = window.document.getElementById? window.document.getElementById('ifrm'): document.all? document.all['ifrm']: null; if ( iframeEl && iframeWin )
{
var docHt = getDocHeight(iframeWin.document); if (docHt != iframeEl.style.height) iframeEl.style.height = docHt + 'px';
}
else
{ // firefox
var docHt = window.document.getElementById('ifrm').contentDocument.height;
window.document.getElementById('ifrm').style.height = docHt + 'px';
}
} function getRetry()
{
getReSize();
setTimeout('getRetry()',500);
}
getRetry();
</script>
by Anna 안나 2009. 1. 5. 13:21
Lot of AJAX Start Page, which one do you prefer?

Google Personalized Homepage
http://www.google.com/ig((-------IMAGE-------))

Netvibes
http://www.netvibes.com((-------IMAGE-------))

Favoor
http://www.favoor.com((-------IMAGE-------))

Start
http://www.start.com((-------IMAGE-------))

Windows Live
http://www.live.com((-------IMAGE-------))

Protopage
http://www.protopage.com/v2((-------IMAGE-------))

My Yahoo!
http://my.yahoo.com((-------IMAGE-------))

Pageflakes
http://www.pageflakes.com

My MSN
http://my.msn.com

HomePortals
http://www.cfempire.com/home

Zoozio
http://www.zoozio.com

My Potu
http://my.potu.com

eskobo
http://www.eskobo.com

ItsAStart
http://itsastart.com

OKRSS
http://www.okrss.com

dodoor
http://www.dodoor.cn

LinkedFeed
http://www.linkedfeed.com

MemeFlow
http://www.memeflow.com/goto

Fold
http://www.fold.com
by Anna 안나 2009. 1. 5. 13:20
ajax를 이용한 파일 탐색기 입니다.

처음에 트리 구조를 공부하다가 만든건데 어쩌다 보니 탐색기가 되어 버렸네요.

조금만 수정 하시면 웹하드로도 사용하실수 있을겁니다.

safari3, FF2 , IE6,7 에서 테스트해보았습니다.

사용하실때 tree.html안의 root경로만 변경하여 주시면 됩니다.

- 반드시 접근할수 있는 경로로 변경해주세요.
- 접근할수 없는 권한의 경로로 이동하면 에러가 나네요.. -.-;

<script language="javascript">
//경로(phth=불러올수 있는 서버 주소(절대경로)) , 리턴되는 값을 받을 함수
root = "접근할수 있는 경로";
xmlHttp("data.php?path="+root,tree.view);
</script>


((-------IMAGE-------)) file.zip
by Anna 안나 2009. 1. 5. 13:17
[ajax & php] PHP와 AJAX를 연동해보자

PHP와 AJAX를 연동해보자라... 참 거창합니다만 실상 알고보면 되게 허섭한 내용입니다 ^^ AJAX란 무엇인가? 복잡한 설명은 패스하고 간단하게 설명합니다.. AJAX는 어떠한 입력폼에 입력하고 전송할때 전송이 완료되어 모든 처리가 끝나기전까지 아무런 작업도 하지 못하고 기다려야 하는 부분이 해소되어 전송하면서도 계속해서 작업을 하거나 빈페이지를 보지 않고 진행상황을 직접 연출하는등 으로 지루함을 달랠수 있는 방법입니다... 간단히 예를 들어보면 우리가 게시판을 접속해서 목록을 보다가 두번째 페이지를 보려고 [2] 라는것을 클릭합니다... 이때 보통은 빈페이지가 보이거나 새로운 페이지를 불러오기 위해 리프래시(새로고침)가 되는 현상을 볼수가 있습니다.. 그러나 AJAX를 이용하게 되면 모든 처리가 완료되어 결과내용이 전달되면 바로 현재 보고있는 상태에서 내용이 바뀌어버립니다.. 그래서 기다릴 필요가 없게 되는거죠.. 그러나 이것도 단점이 있으니 지원하지 않는 브라우저나 OS가 있으며 어떤 오류가 생길때 해당 오류에 대해 정확히 파악을 할수가 없을때가 있다는것이 단점입니다.. 서론은 여기까지 하기로 하고요^^ 그럼 어떻게 연동을 하게 될까요.. 입력폼등 출력페이지를 제작할때 xmlHttpRequest 를 이용해서 하실수 있는데 이를 구성하는 방법이 쉽지많은 않습니다... 해서 간단한 소스를 보겠습니다... function createHttpRequest()
{ if(window.ActiveXObject) {
//Win e4,e5,e6용

try {
return new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) { // 위 부분이 실패하게 되면
try { // 여기로 넘어옵니다..
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) { // 이마저도 실패되면 아무값도 리턴하지 않습니다..
return null;
}
}
}
else if(window.XMLHttpRequest) { //그밖에 브라우저
// Win Max Linux m1,f1,o8,Mac s1 Linux k3 용 return new XMLHttpRequest();
}
else {
return null;
}
}
이렇게 함수로 묶었습니다.. 요것을 <script> 와 </script> 사이의 필요에 의해서 불러서 사용할수 있습니다.. ajax = createHttpRequest(); // 이런식으로 연결해서 사용할수 있습니다.. 그러나 요렇게만 해서 사용하게 되면 한글의 경우는 전송시 깨져서 나가기때문에 UTF-8 로 변경하는 작업이 필요하게 됩니다... 그부분을 함수로 묶어봤습니다... function sendRequest(callback,data,method,url,async,sload,user,password)
{ //callback 인자는 전송후 전달받은 값이 있을경우 처리할 곳을 의미합니다.. //data 는 전달시 필요한 데이터가 있으면 붙여주는곳이며 //method 는 POST 또는 GET 방식중 선택합니다.. //url 은 전송할 주소를 지정하는 곳이며 //async 비동기식이면 true 동기라면 false 로 지정합니다.. //sload 는 수퍼로드로 강제로드(true) 혹은 생략 false 로 사용할수 있습니다. //user 와 password 는 인증페이지인경우 전달하여 접근하도록 하는 인자입니다.. //XMLHttpRequest 오브젝트 생성 var oj = createHttpRequest();
if( oj == null ) return null; //강제 로드의 설정 var sload = (!!sendRequest.arguments[5])? sload:false;
if(sload || method.toUpperCase() == 'GET') url += "?"; // 메소드가 GET 이면 주소에 ?를 붙여주어 data 값을 전달하도록 합니다..
if(sload) url = url+"t="+(new Date()).getTime(); oj.onreadystatechange = function ()
{ // 전달된 값이 존재하면 콜백함수로 넘겨줍니다...
if ( oj.readyState == 4 ){ // 이부분은 상태가 전송완료인경우에 해당됩니다..
callback(oj);
}
}

// URL 인코딩
data = uriEncode(data); // 넘겨주는 data 값에 한글이 있을수 있으므로 utf-8 형식으로 포멧합니다..
if(method.toUpperCase() == 'GET') {
url += data;
} oj.open(method,url,async,user,password); //전송합니다.. //해더 application/x-www-form-urlencoded 설정 setEncHeader(oj); //헤더 설정하는 부분으로 케릭터셋도 함께 설정됩니다..
//send 메소드 oj.send(data); //전송할 data 값이 있으면 전송합니다.. //URI 인코딩 헤더 설정 function setEncHeader(oj) {
var contentTypeUrlenc = 'application/x-www-form-urlencoded; charset=UTF-8'; if(!window.opera) {
oj.setRequestHeader('Content-Type',contentTypeUrlenc);
} else {
if((typeof oj.setRequestHeader) == 'function')
oj.setRequestHeader('Content-Type',contentTypeUrlenc);
}
return oj;
}
//URL 인코딩
function uriEncode(data) { if(data!= "") {
//&와 = 로 일단 분해해서 encode

var encdata = '';
var datas = data.split('&');
for(i=1;i<datas.length;i++) {
var dataq = datas[i].split('=');
encdata += '&'+encodeURIComponent(dataq[0])+'='+encodeURIComponent(dataq[1]);
}
} else {
encdata = "";
}
return encdata; }
return oj; } 본 소스는 AJAX 입문이라는 책에서 참고한 내용입니다.. 실질적으로 사용할때는 onclick 또는 링크에 sendRequest("콜백함수명","전달할 데이터명","전송방식","전송할 주소","엔씽크","수퍼로드"); 형식이 되겠습니다... 콜백함수가 onloadl 이라면 function on_loadedl(oj) {
var res = decodeURIComponent(oj.responseText); document.all.testview.innerHTML = res;
} 이런식으로 전달받은 값을 사용하여 출력해줄수 있겠습니다... testview 는 전달받은 내용을 출력해줄 Div(레이어)나 테이블의 ID값등으로 지정하시면 되겠습니다.. 상당히 힘들수도 있는 부분임에도 끝까지 읽어주셔서 감사합니다..^^ 출처 : 우 린친구닷컴 - [ajax & php] PHP와 AJAX를 연동해보자 - http://urin79.com/zb/?mid=blog&category=100313&page=5&document_srl=375257
by Anna 안나 2009. 1. 5. 13:16
가능하기만 하다면, RESTful 방식으로 Ajax 기반 애플리케이션을 포함하여 웹 애플리케이션을 구현한다면 많은 버그를 피할 수 있습니다. 하지만, REST (REpresentational State Transfer)의 함정은 비슷한 XMLHttpRequests를 통해 중복 데이터를 보내는 것입니다. 이 글에서는 세션 쿠키를 활용해서 서버 측 상태를 관리하여 클라이언트-서버 트래픽을 줄이는 방법을 설명합니다. 머리말 HTTP에 관한 기정 사실은 엄청난 힘과 취약점이다: HTTP는 Stateless 프로토콜이다. HTTP 서버 리소스로의 요청은 멱등(idempotent)이어야 하며, 호출 시 같은 요청이 같은 결과를 리턴해야 한다. 멱등성(Idempotency)은 REST의 중심적인 개념이다: 클라이언트 정보를 인코딩한 요청이 그 요청과 같은 데이터를 리턴해야 한다. REST 철학과는 반대로, Ajax 애플리케이션들은 거의 언제나 Stateful이다. 웹 애플리케이션의 특정 필드나 영역은 서버 데이터의 현재 상태를 반영하면서, 클라이언트 JavaScript 폴링(poll)으로 현재 상태를 주기적으로 쿼리 하는데 사용된다. (이것을 보다 푸시(push) 지향적인 것으로 할 수 있는 방법이 있지만, 이 글의 논점에서는 벗어난다.) 하지만, 웹 애플리케이션은 서버가 다음 폴링 이벤트에 대해 알아 두어야 할 것을 지속적으로 트래킹 해 줄 것을 기대하고 있다: 클라이언트가 보았거나 보지 못한 데이터, 이미 발생했던 인터랙션이 바로 그것이다. Ajax 애플리케이션을 기술적으로 RESTful로 만드는 한 가지 일반적인 방법은 최신 데이터에 대한 모든 쿼리가 고유 URI를 갖도록 하는 것이다. 이를 테면, URL로 인코딩 된 매개변수 또는 숨겨진 폼 변수에 UUID를 포함시킨다; 예를 들어, XMLHttpRequest 객체는 다음과 같은 리소스를 얻게 된다. http://myserver.example.com?uuid=4b879324-8ec0-4120-bba6-890eb0aa3fc0
바로 다음 폴링 이벤트 시, 1초 후에 다른 URI가 열린다. 멱등성은 트릭이 필요하다! "같은 데이터"의 의미를 이해하는 것은 생각보다 어려운 문제이다. 이상적으로만, URI가 언제나 동일한 데이터를 리턴한다. 결국, 정적인 웹 페이지는 콘텐트가 수정될 때 변할 것이다. (다시 말해서, 오타가 공개된 아티클에서 수정된다.) 이러한 멱등성 뒤에 숨은 개념은 변경 사항들이 GET 요청 자체의 직접적인 결과가 되어서는 안된다는 것이다. 이와 같은 지속적으로 변하는 리소스를 갖는다는 것은 매우 합리적인 접근 방식이다. http://myserver.example.com/latest_data/
문제는, "latest_data"를 구성하고 있는 것이 데이터 검색 여부, 시기, 사람과는 다른 것에 의존한다는 점이다. 서버는 완벽히 RESTful이 될 수 있지만, 여전히 "상태"를 반영한다. 최신 데이터 얻기 필 자의 동료인 Miki Tebeka와 필자는 JavaScript XMLHttpRequest() 객체를 사용하여, 서버에서 최신 데이터를 자주 폴링하는 웹 애플리케이션을 개발하는 상황을 직면했다. 이 글에서 필자가 제공한 Python 서버 예제는 Miki가 만들었던 인-하우스 모듈에 영감을 받은 것이지만, 더욱 단순화 되고 향상되었다. 여기에 두 가지 문제가 생겼다. 하나는 이전 요청 후에 어떤 것도 변하지 않았을 때 중요한 메시지를 보내지 않는다는 것이다. 두 번째 문제는 중복 데이터를 생성하는데 데이터베이스나 전산 리소스를 과도하게 사용하지 않는다는 것이다. "Not Modified" 문제는 HTTP 프로토콜에서 바로 해결된다. 하지만 이러한 정확한 솔루션이 사용되고 있지는 않다. 우리가 해야 할 일은 HTTP 304 상태 코드를 리턴하는 것이다. 이것은 304 상태를 Ajax 코드가 검사하게 하여, 만약 발견될 때에는 폴에서 보내진 데이터(부재)에 기반하여 클라이언트 애플리케이션 상태를 변경하지 말라는 것이다. 서 버 리소스 문제는 이전 데이터를 캐싱하고 최근 추가된 것을 모음으로써 해결될 수 있다. 이 솔루션은 전체 데이터 세트가 상호 의존적이기 보다는 "최신 데이터"가 개별적인 데이터 아이템들로 구성되어 있을 경우와 관련이 깊다. Listing 1을 보자:
Listing 1. 세션 실행 서버 코드: server.cgi
from datetime import datetime session = ClientSession() old_stuff = session.get("data", []) # Retrieve cached data last_query = session.get("last", None) prune_data(old_stuff, last_query) # Age out really-old data new_stuff = get_new_stuff() # Look for brand-new data if not new_stuff: print "Status: 304" # "Not Modified" status else print session.cookie # New or existing cookie print "Content-Type: text/plain" print all_stuff = old_stuff + new_stuff session["data"] = all_stuff session["last"] = datetime.now().isoformat() print encode_data(all_stuff) # XML, or JSON, or... session.save()
ClientSession 클래스를 주목해 보자. 기본적으로, 캐싱된 old_stuff에 상응하는 쿠키를 갖고 있는 각 클라이언트를 트래킹 해야 한다:
Listing 2. 세션 관리하기
from os import environ from Cookie import SimpleCookie from random import shuffle from string import letters from cPickle import load, dump COOKIE_NAME = "my.server.process" class ClientSession(dict): def __init__(self): self.cookie = SimpleCookie() self.cookie.load(environ.get("HTTP_COOKIE","")) if COOKIE_NAME not in cookie: # Real UUID would be better lets = list(letters) shuffle(lets) self.cookie[COOKIE_NAME] = "".join(lets[:15]) self.id = self.cookie[COOKIE_NAME].value try: session = load(open("session."+self.id, "rb")) self.update(session) except: # If nothing cached, just do not update pass def save(self): fh = open("session."+self.id, "wb") dump(self.copy(), fh, protocol=-1) # Save the dictionary fh.close()
Ajax 호출 만들기 서버 캐싱이 잘 되었다면, 데이터를 폴링하는 JavaScript는 매우 간단하다. 우리에게 필요한 것은 Listing 3과 같은 것이다:
Listing 3. 최신 데이터를 서버에서 폴링하기
var r = new XMLHttpRequest(); r.onreadystatechange=function() { if (r.readyState==4) { if (r.status==200) { // "OK status" displayData(r.responseText); } else if (r.status==304) { // "Not Modified": No change to display } else { alertProblem(r); } } } r.open("GET",'http://myserver.example.com/latest_data/',true) r.send(null);
displayData()와 alertProblem()의 구현은 예제에는 지정되지 않는다. 아마도, 전자는 특정 방식으로 받은 응답을 파싱 또는 처리해야 한다. 상세한 것은 JSON, XML 등 어떤 포맷이 데이터를 보내는데 사용되는지와, 실제 애플리케이션 요구 사항에 의존한다. 더욱이, 빠른 예제는 한 번에 폴링하는 방법만 보여준다. 장기 실행 애플리케이션에서, 우리는 반복적으로 setTimeout() 또는 setInterval() 콜백에 이러한 요청을 만든다. 또는, 애플리케이션에 기반하여, 폴링은 뒤이은 특정 클라이언트 애플리케이션 액션이나 이벤트를 발생시킨다.
((-------IMAGE-------)) ((-------IMAGE-------))
((-------IMAGE-------))
위로

요약 이 글에서는 Python으로 작성된 코드를 설명했지만, CGI 또는 기타 서버 프로세스를 프로그래밍 하는데 사용되는 거의 모든 언어에도 같은 디자인이 적용된다. 일반적인 개념은 단순하다. 클라이언트 쿠키를 사용하여 캐싱된 데이터를 구분하고, 마지막 폴링 이벤트 후에 어떤 새로운 데이터도 발생하지 않았다면 304 상태를 보낸다. 여러분의 서버 프로그래밍 언어가 무엇이든지, 프로그램은 거의 같을 것이다. 많은 에러를 보여주지는 못했지만, 디자인은 쿠키를 사용할 수 없는 곳에서 작동을 수정하는데 있어서 매우 강력한 힘을 발휘한다. 클라이언트가 관련된 세션 쿠키를 갖고 있지 않으면, 이것이 쿠키를 받아들이지 않거나, 이것이 새로운 세션의 첫 번째 폴이기 때문에, old_stuff는 간단히 빈 리스트이고, 리턴된 데이터는 new_stuff의 일부가 된다. 추가할 가치가 있는 또 다른 기능은 현재 세션 상태를 보내는 클라이언트 메시지이다: 이것은 애플리케이션 디버깅과 일관성 없는 상태를 규명하는 방식으로서 사용하기에 알맞다. 캐시를 플러시 할 때 여러분이 잃게 되는 것은 서버 로드와 일정 대역폭이다. 그렇다고 해서 이것이 기반 멱등성을 위반하지는 않는다.

참고자료 Wikipedia 제공: REST의 기본 원리 소개.

developerWorks SOA와 웹서비스 존

developerWorks Ajax 리소스 센터
by Anna 안나 2009. 1. 5. 13:15
| 1 2 3 4 5 |