달력

42024  이전 다음

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
http://www.scriptdoc.org/specification.htm

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

Home Page | Forums

Introduction

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

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

The section for each tag includes the following information:

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

Reference

The following tags are valid for code documentation:

@alias

ID for a class or function.

Applies to: Any

Syntax

@alias fooBar

Description

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

Example

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

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


@author

Author of a JavaScript file or function.

Applies to: Any

Syntax

@author Author-name [email]

Description

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

Example

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

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

@classDescription

Description of the class.

Applies to: Function

Syntax

@classDescription Description

Description

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

Example

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

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

@constructor

Shows that a function is a constructor for a class.

Applies to: Function

Syntax

@constructor

Description

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

Example

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

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

@deprecated

Signifies that a function or a property has been deprecated.

Applies to: Function or property.

Syntax

@deprecated

Description

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

Example

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

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

@exception

Specifies the type of exception thrown by a function.

Applies to: Function

Syntax

@exception {Exception} Exception-description

Description

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

Example

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

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

@id

Unique identifier for a function or property.

Applies to: All

Syntax

@id identifierName

Description

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

Example

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

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

@memberOf

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

Applies to: Function, Property.

Syntax

@memberOf Class

Description

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

Example

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

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

@method

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

Applies to: Function

Syntax

@method

Description

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

Example

This example shows a @method tag.

/**
* @method
*/

@namespace

Creates the namespace prefix for a library file.

Applies to: File

Syntax

@namespace namespaceName

Description

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

Example

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

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

/**
 * @namespace snazzyLib.ajax
 */

@param

Use @param to tag each parameter for a function.

Applies to: Function

Syntax

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

Description

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

Examples

Standard example

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

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

Optional parameter example

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

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

Multiple objects example

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

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


@projectDescription

Gives a description of a JavaScript file.

Applies to: File.

Syntax

@projectDescription Description

Description

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

Example

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

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


@return

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

Applies to: Function

Syntax

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

Description

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

Example

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

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

@sdoc

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

Applies to: File

Syntax

@sdoc filePath

Description

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

Example

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

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

@see

Links to another related class or function.

Applies to: Any

Syntax

@see Class | #Function | Class#Function

Description

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

Examples

Function example

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

/**
 * @see #foo
 */

Class example

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

/**
 * @see fooBar
 */

Function in another class example

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

/**
 * @see fooBar#foo
 */

@since

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

Applies to: File, Function, Property

Syntax

@since Version-number

Description

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

Example

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

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

@type

Specifies what data type a property is.

Applies to Property

Syntax

@type {Type}

Description

Specifies what data type a property is.

Example

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

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

@version

Specifies the version number of the JavaScript file or class.

Applies to: Any

Syntax

@version Version-Number

Description

Specifies the version number of the JavaScript file or class.

Example

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

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

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

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

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

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


<pre style="word-wrap: break-word"> 내용... </pre>

또는 table 에 table-layout: fixed 스타일도 같이 주면 해결된다.
Posted by tornado
|

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

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


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

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

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

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

  </script>
 </HEAD>

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

 </BODY>
</HTML>

Posted by tornado
|

펌질 했습니다. ^^

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


JavaScript Throw Statement

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



 

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

throw문

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

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

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

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

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

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


Accordion for Script.aculo.us

Technieken: Javascript

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

How to use

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

Include the file in your webpage
Code:

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



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

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



And put just before the tag the Javascript:
Code:

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



Parameter explanation
Parameter 1
A CSS Selector which selects all titles

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

Parameter 3 Optional
A list of options, see below

Options

duration - Sets how long the effect should take

Example:
Code:

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



_____________________________________________

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

Example:
Code:

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



______________________________________________________

event_trigger - On which event should the body be shown

Example:
Code:

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



Events

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

Code

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

var Accordion = Class.create();

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

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

Effect.Accordion = Accordion;
Posted by tornado
|

CSS 참고할곳

DHTML/CSS 2007. 6. 14. 11:33

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

[펌] Internet Explorer CSS bug fixes  (0) 2010.07.05
CSS Layout 공부하기...  (0) 2007.04.18
CSS Tab Designer  (0) 2006.10.09
CSS Navigation Techniques (37 entries).  (0) 2006.09.06
Posted by tornado
|

심심해서 만들어본 간단한 롤오버 메뉴



<html>
 <head>
  <style>
 body {
  margin: 0;
  padding: 0;
  font-size: 0.75em;
  line-height: 1.5em;
  font-family: Dotum, "돋움", sans-serif;
 }

 #navi {
  width: 100%;
  text-align: center;
  background-color: #BBCCCC;
 }

 #navi a{ text-decoration: none; color: #78777C}
 #navi a:hover {
  position:relative;
  z-index:10;
  letter-spacing:0;
  text-decoration: underline;
 }

 #navi span { width: 110px; line-height: 27px;
  line-height:27px;
  cursor:hand;
 }

 #navi ul li a span { width: 110px;}
 #navi a:hover span  { background-color: #A2BFBF;}

  </style>
 </head>

 <body>

  <div id="navi">
   <span><a href=""><span id="naviLink">메뉴 1</span></a></span>
   <span><a href=""><span id="naviLink">메뉴 1</span></a></span>
   <span><a href=""><span id="naviLink">메뉴 1</span></a></span>
   <span><a href=""><span id="naviLink">메뉴 1</span></a></span>
   <span><a href=""><span id="naviLink">메뉴 1</span></a></span>
   <span><a href=""><span id="naviLink">메뉴 1</span></a></span>
  </div>
 </body>
</html>





Posted by tornado
|


출처 : http://www.mozilla.or.kr/docs/web-developer/standard/index.html

반드시 읽어봐야 하는 아주 중요한 문서.





실전 웹 표준 가이드 (2005)

본 가이드는 XHTML, CSS, DOM, ECMAScript 등 모든 웹 표준에 대한 이슈를 새롭게 정리하고, 웹 개발 프로젝트에서 표준을 준수하는 방법을 제공하는 가이드 입니다.

목 차

  • 웹 표준이란 무엇인가?
  • 실전 XHTML 가이드
    • XTHML 소개
    • XHTML 일반 문법 준수
    • 구조적 XHTML 사용 방법
  • 실전 CSS 레이아웃
    • CSS 개념 및 소개
    • CSS 레이아웃(LAYOUT) 기초
    • 실전 예제를 통한 CSS 레이아웃
    • 고급 CSS 레이 아웃
  • 실전 DOM/Script 가이드
    • W3C DOM vs. MS DOM
    • 표준 JAVASCRIPT 사용 방법
    • 올바른 플러그인(PLUGIN) 사용
  • 실전 표준 웹 프로그래밍
    • 표준 MIME 타입 설정
    • 표준 문자 인코딩 지정
  • 실전 웹 표준 개발 프로세스
    • 현재 프로세스 소개(Waterfall 방식)
    • 개선된 모델(퍼블리셔 중심)
    • 새로운 개발 프로세스
  • 맺음말
  • 부록 : 웹 표준 사양-브라우저 호환차트
- URL: http://www.mozilla.or.kr/docs/web-developer/web-standard-guide-2005.pdf
- 인쇄 버전 : PDF 파일 (223pp), PDF 파일(부록 포함, 305pp)




Posted by tornado
|
http://www.subcide.com/tutorials/csslayout/

쉽게 잘 나와있어서 보고 따라하기 좋음..

하지만~~~ 나도 안해봤다는거.

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

[펌] Internet Explorer CSS bug fixes  (0) 2010.07.05
CSS 참고할곳  (0) 2007.06.14
CSS Tab Designer  (0) 2006.10.09
CSS Navigation Techniques (37 entries).  (0) 2006.09.06
Posted by tornado
|

--------------------------------------------------------------------------
ext-prototype-adapter 을 이용하여 prototype, Scriptaculous 사용하기
--------------------------------------------------------------------------

자세한 내용은 http://extjs.com/ 와 다운로드 받은 Examples 에서 봐야함
오늘은 맛보기만 ㅎㅎㅎㅎㅎ
--------------------------------------------------------------------------
테스트할 디렉토리 구조.

기본 테스트 디렉토리     ==>  d:\html\ext_test
JS 파일 디렉토리           ==>  d:\html\ext_test\common\js
CSS 파일 디렉토리        ==>  d:\html\ext_test\common\css
EXT-JS 이미지 디렉토리 ==>  d:\html\ext_test\common\images ,
                                          d:\html\ext_test\common\raw_images

1. http://script.aculo.us/downloads 에서 스크립타큘로스를 다운로드 받는다.(1.7 버전 이상)

압축을 풀면 아래와 같은 디렉토리 구조가 보인다.

----- lib  
  |-- src
  |-- test


lib 디렉토리에 있는 prototype.js 를 JS 파일 디렉토리에 복사한다.
src 에 있는 파일중 unittest.jsp 를 제외하고 JS 파일 디렉토리에 복사한다.


2. http://extjs.com/download 에서 ext-js 를 다운로드 받는다.

압축을 풀면 디렉토리가 여러개 있고 js 파일들도 보이는데 스크립타큘로스와 프로토타입을
사용할 것이기 때문에 필요한것만 복사한다.


ext-prototype-adapter.js
ext-all.js

위의 두 파일을 JS 파일 디렉토리에 복사한다.

다음으로 resource 디렉토리에 있는 images 와 raw-images 디렉토리를 common 디렉토리에 복사한다.


3. 첫번째 예제 작성

기본 테스트 디렉토리(d:/html/ext_test) 에 beginner_1.html 로 파일을 하나 만든다.

-----  beginner_1.html -----
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
 <head>
  <title> New Document </title>

    <link rel="stylesheet" type="text/css" href="./common/css/ext-all.css">
    <link rel="stylesheet" type="text/css" href="./common/css/ytheme-aero.css">
    <style type="text/css">
     body {
       font-family: Tahoma,Arial,Helvetica,sans-serif;
       font-size:12px;
       color:#333;
       padding: 20px;
     }
    </style>

    <script type="text/javascript" src="./common/js/prototype.js"></script>
    <script type="text/javascript" src="./common/js/scriptaculous.js"></script>
    <script type="text/javascript" src="./common/js/ext-prototype-adapter.js"></script>
    <script type="text/javascript" src="./common/js/ext-all.js"></script>


 <script type="text/javascript" language="javascript">
 <!--
  Ext.onReady(function() {
   alert("테스트 합니다");
  });
  //-->
  </script>
 </head>

 <body>

  <input type="button" id="myButton" value="My Button" />
 
 </body>
</html>

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

위의 내용을 실행 했을 경우 ALERT 창이 뜨면 된것이다.

간단하게 버튼하나 만들어봅시다.

/*----  수정된 EXT.onReady()  시작                        -----*/
/*----  EXT.onReady() 안의 내용을 아래와 같이 수정 ---- */

 Ext.onReady(function() {
  var paragraphClicked = function(e) {  
    var paragraph = Ext.get(e.target);
    //paragraph.highlight();
    Ext.MessageBox.show({  
     title: '!!! 타이틀 !!!',  
     msg: '메세지 박스 입니다...',  
     width:800,
     buttons: Ext.MessageBox.OKCANCEL,  
     animEl: paragraph
    });
  }
 
  Ext.get('myButton').on('click', paragraphClicked);
 });
/*---- 수정된 EXT.onReady()  끝 -----*/

실행하면 ok / cancel 버튼이 있는 메세지 박스가 뜰것이다.


만약 클릭한 버튼이 어떤건지 알아내기 위해서는 아래와 같이 콜백함수를 지정하면 된다.


--------------------------------------------------------------------------
 Ext.onReady(function() {
  var paragraphClicked = function(e) {  
    var paragraph = Ext.get(e.target);
    //paragraph.highlight();
     Ext.MessageBox.show({  
     title: '!!! 타이틀 !!!',  
     msg: '메세지 박스 입니다...',  
     width:800,
     buttons: Ext.MessageBox.OKCANCEL,  
     
     animEl: paragraph,
     fn : showResult    
    });
  }
 
  Ext.get('myButton').on('click', paragraphClicked);


  function showResult(btn){
   alert("눌러진 버튼은 " + btn + " 입니다");
  };

 });
--------------------------------------------------------------------------

방대한 기능들을 자세히 다 알려면 시간좀 걸리겠군.

Posted by tornado
|
사용자 삽입 이미지


내용이 좋을것 같은 느낌 ^^

아래는 강컴에서 발췌한 도서소개 임

도서특징
Web 2.0 시대의 Ajax 애플리케이션 개발자, 설계자, 분석가를 위한 필독서 객체지향 Ajax 애플리케이션 구현 방법을 상세하게 제시 prototype.js 소스 코드 완전 분석
Ajax는 그 자체는 물론이고 Web 2.0 실현의 초석이 된다. 이 책은 이런 시대적 흐름을 주도하고 미래 지향적인 개발자, 설계자, 분석가의 요구를 충족시키기 위해 쓰여졌다.

객체지향 방법으로 애플리케이션을 개발하는 것은 필요충분조건이다. 하지만 객체지향 방법은 서버 사이드 애플리케이션의 전유물이었고, 어긋난 개발 환경과 접근으로 인해 정작 중요한 클라이언트 사이드 애플리케이션은 보조 역할을 하였다. 하지만 Ajax는 이런 형태에 새로운 패러다임을 제시하였으며 prototype.js가 이를 증명하였다. 이 책은 prototype.js 프레임웍을 이용하여 객체지향 방법으로 Ajax 애플리케이션을 구현할 수 있는 방법을 밑바탕부터 제시한다.

prototype.js는 세계적으로 인정받는 Ajax 프레임웍이다. 이에 대해서는 이미 많은 전 세계 개발자들에 의해 검증이 끝난 상태이다. 그렇다면 어떤 점이 개발자들의 마음을 사로잡게 되었는지 속을 들여다보고 파헤쳐봐야 한다. 이 과정을 통해 자연스럽게 실력이 향상됨은 물론이고, Ajax 애플리케이션 구현의 새로운 세계도 접할 수 있다. 이 책은 prototype.js 소스 코드를 라인 단위로 분석하였다. 코드의 작성 목적 및 이유를 분석하였고 아울러 기술적인 밑바탕을 제시하였다.


[머리말]

『Ajax prototype.js: 프로토타입 완전분석』은 새로운 패러다임의 Ajax 애플리케이션 구현을 위해 빠르고 쉬운 지름길로 여러분을 안내할 것이다.

『Ajax prototype.js: 프로토타입 완전분석』은 선택이 아니라 필수가 될 것이다. 이 책을 안보고 Ajax 애플리케이션을 논해서는 곤란하다. 자바스크립트가 객체지향 언어가 아니므로 객체지향을 구현할 수 없다고 한다면, 이 또한 곤란하다. 이런 말들은 이 책을 읽고 난 후에는 필요없는 말이 될 것이다. 필자는 이를 확신한다. 책을 다 읽고 난 후 필자가 왜 이렇게 강하게 주장했는가를 독자는 이해하게 될 것이다.

prototype.js가 현존하는 Ajax 프레임웍 중에서 가장 좋다고 하는 것은 이미 전 세계 개발자들에 의해 검증이 끝났다. 이제 prototype.js는 Ajax 애플리케이션을 개발할 때 없어서는 안될 존재가 되었다. prototype.js는 자바스크립트로 만들어져 있지만, 그 동안 자바스크립트로 구현하기에 어려움이 있다고 생각했던 객체지향 방법을 제시하고 증명하였다.

이 책의 목적은 prototype.js를 이해하는 것이며, 이를 통해 객체지향 방법으로 자바스크립트 코드를 작성하는 것이다. prototype.js를 이해하기 위해서는 자바스크립트 코드를 분석해야 하며, 분석하기 위해서는 코드를 작성한 논리적 배경을 이해해야 한다. 이 책은 이러한 흐름으로 구성돼 있다.

prototype.js의 클래스, 오브젝트, 메서드 등을 이해하기 위해서 사전 이해가 필요한 부분이 있다면 먼저 이를 설명하고 prototype.js 소스 코드를 설명하였다. 또 prototype.js 소스 코드를 설명한 후 이를 보충 설명하는 반대의 경우도 있다. 이러한 형태는 prototype.js 소스 코드에 대해 보다 논리적이고 합리적으로 접근하기 위함이다.

자바스크립트에 대한 개념이 전혀 없는 초급자라면 자바스크립트에 대한 책을 먼저 본 후 이 책을 볼 것을 권한다. 왜냐하면 자바스크립트의 아주 기초적인 내용은 다루지 않기 때문이다.

창조는 모방으로부터 시작된다는 말이 있다. 유아기에 엄마의 말을 따라 하면서 자연스럽게 말을 배우듯이 객체지향 방법으로 작성된 prototype.js 소스 코드를 분석하면서 자연스럽게 객체지향 방법으로 접근할 수 있으며, prototype.js에서 제공하는 프레임웍을 이용하여 보다 유려한 Ajax 애플리케이션을 개발할 수 있다.

이 책은 크게 두 가지 관점에서 접근할 수 있다. prototype.js에서 제공하는 클래스와 메서드를 사용하여 Ajax 애플리케이션을 개발하는 측면과 한발 더 나아가 prototype.js 소스 코드를 내 것으로 만드는 측면이다. 전자는 즉시 Ajax 애플리케이션을 구현할 수 있는 반면, 다소 밑바탕이 약한 행보가 될 수 있다. 후자는 더욱 기반이 튼튼하고 유려한 Ajax 애플리케이션을 개발할 수 있는 반면 시간이 좀 더 필요하다. 이 책을 어떤 관점으로 읽을 것인가에 대한 판단은 독자의 몫이다.

저자소개
김영보 http://cafe.naver.com/requirements.cafe
1979년 코오롱 전산실에 입사한 후 28년 동안 소프트웨어를 개발해온 베테랑 개발자이며 분석가이다. 장인 정신을 추구하며 아직도 시스템 개발 현장에 있는 희귀한 사람이기도 하다. 현재는 시스템 개발, 개발자를 위한 기고, 강의/세미나 등을 하고 있으며, 네이버에서 “Ajax와 요구공학” 카페를 운영하고 있다. 저서로는『요구분석을 위한 Event Process 모델링』(2005.11 가메출판사), 『Ajax 활용』(2006.4 가메출판사)이 있다.
Posted by tornado
|



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

 <script language="javascript" type="text/javascript" src="http://www.javarush.com/common/js/prototype.js"></script>
 <script language="javascript" type="text/javascript" src="http://www.javarush.com/common/js/scriptaculous.js"></script>



 


<div style="margin-top: 20px; height: 580px;">
 <div id="photoPanel1" style="position: absolute; "><img src="http://www.javarush.com/images/img1.jpg"  /></div>
 <div id="photoPanel2" style="position: absolute; display: none; "><img src="http://www.javarush.com/images/img2.jpg"  /></div>
 <div id="photoPanel3" style="position: absolute; display: none; "><img src="http://www.javarush.com/images/img3.jpg" /></div>
 <div style="position: absolute; margin-top: 450px;">
 <table border="0" cellpadding="10" cellspacing="5" >
 <tr>
  <td style="background-color: red; width: 70px; height: 7px; cursor: hand;" onmouseover="changeMainImage('photopanel1');"></td>
  <td style="background-color: green; width: 70px; height: 7px; cursor: hand;" onmouseover="changeMainImage('photopanel2');"></td>
  <td style="background-color: blue; width: 70px; height: 7px; cursor: hand;" onmouseover="changeMainImage('photopanel3');"></td>
   </tr>
 </table>
  </div>
</div>


<script language="javascript" type="text/javascript">
<!--

 var choicePanel = document.getElementById('photopanel1');
 
 function changeMainImage(arg1){
  var obj = document.getElementById(arg1);
 
  if(obj){
   if(obj.id != choicePanel.id){
    new Effect.Fade(choicePanel, { duration : 0.8 , afterFinishInternal : function() {
     new Effect.Appear(obj, { duration : 0.8 } )
    }
   } );
   }
  
   choicePanel = obj;
  }
 } 
 
 var cnt = 1;
 
 function autoChange(){
  changeMainImage('photopanel' + cnt);
 
  setTimeout("autoChange()", 5000);
  cnt++;
  if(cnt >= 4){
   cnt = 1;
  }
 }
 autoChange();
//-->
</script>


Posted by tornado
|

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

http://www.christofwagner.com/  (0) 2007.02.05
[참고할곳] http://www.endless.com/  (0) 2007.01.19
The Lightbox Effect without Lightbox  (0) 2007.01.11
http://prototype-window.xilinus.com/  (0) 2006.11.30
[ajax] 우편번호 찾기 초보버전  (2) 2005.08.22
Posted by tornado
|
Posted by tornado
|

[링크] dhtml grid control

DHTML 2007. 1. 25. 16:54
Posted by tornado
|

http://www.endless.com/


잘 만들었네~

Posted by tornado
|

출처 : http://www.sitepoint.com/print/painless-javascript-prototype

 

SitePoint Sponsor

Article


Dan Webb

Dan Webb Dan is a rehabilitated DHTML hacker turned web application developer for Vivabit, organisers of the @media conference. His current weapons of choice are Ruby on Rails and modern, unobtrusive DOM scripting. On those occasions he's not programming, he enjoys blogging on Vivabit's blog, (The Web's Bollocks), hording vast amounts of vinyl and eating cheese slices.

Dan Webb has written 2 articles for SitePoint with an average reader rating of 9.3.

View all articles by Dan Webb...

Painless JavaScript Using Prototype

By Dan Webb

February 22nd 2006

Reader Rating: 9.6

Prototype is an object oriented JavaScript [1] library (written by Sam Stephenson and friends) that makes JavaScript fun. So it says on the site [2], anyway. Those of you who are familiar with the open source community's latest and greatest application framework, Rails, may recognise Prototype as it actually forms the backbone of Rails' JavaScript helper. However, Prototype can be used independently of Rails to aid the coding of many JavaScript doodads and Web 2.0 thingy wangles.

Personally, I think the jury's out on the whole 'fun' JavaScript thing, but nevertheless Prototype is a really well executed JavaScript library which, although the situation has been improving of late, has had notoriously sparse documentation. This article provides a whirlwind tour of the whole library. It aims to give you enough examples and resources to get started using Prototype in your DOM [3] scripting projects.

First, we'll examine the basic building blocks of Prototype: its $ functions, its additions to the String, Number, Array [4] and Function objects, its form handling capabilities and its DOM functions. Then, we'll move on to look at Prototype's well-known AJAX [5] helpers. Finally, we'll finish with a brief discussion of other interesting projects that are based on it.

I'd like to note that the current stable version of Prototype at time of writing is 1.4.0. I have a feeling that the library will change quite quickly in response to Rails' lightning-quick development cycle, so things will change. The final boring note is that at this time Prototype only supports the newer browsers -- as you might expect of a DOM and XMLHttpRequest based library. See the Prototype site [6] for details of browser support.

Getting Started

The latest version of Prototype can be downloaded from the prototype site [7]. Simply download prototype.js and link it to your pages with a <script> tag:

<script type="text/javascript" src="path/to/prototype.js"></script>

If you're on Rails, you don't need to download Prototype: it's included in the distribution. You can include it into your views by putting this into the <head> of your pages:

<%= javascript_include_tag 'prototype' %>

Now, let's get into it!

Prototype's Little Helpers

One of the really nice things about using Prototype is the deadly simple helper functions that it provides for very common scripting tasks. The $ function has already been getting some attention. Give it one or more element IDs, and it'll return references to them:


// reference to the element with the ID 'nav'
$("nav")
// an array of element references
$("img1", "img2", "img3")

It's like a souped-up document.getElementById and it's amazing how much more convenient coding seems when you use it.

Another incredibly useful function is document.getElementsByClassName, which does what it says on the tin: it takes a CSS [8] class name and returns a list of all elements with that class:

// all elements with class 'navlink'
document.getElementsByClassName("navlink")
// all elements with class navlink and inside the element with ID 'nav'
document.getElementByClassName("navlink", $("nav"))

Also, as this article was being written, Prototype version 1.5.0_rc0 gained the powerful $$ function, which allows you to select elements using standard CSS selector syntax:

// an array of all input elements inside 'commentform'
$$("#commentform input")
// an array of all links with the class 'external'
$$("a.external")

Please note that, at the time of writing, unless you download the very latest version of Prototype from Subversion [9], this function won't be available to you.

$F takes an ID and returns the value of any form field, for instance, a select box like this:

<select name="country" id="country">
 <option selected="selected" value="UK">United Kingdom</option>
 <option value="FR">France</option>
 ...
</select>

$F('country') // 'UK'

Making JavaScript Suck Less

Oops, I've stolen another JavaScript library [10]'s tag line. JavaScript library developers just can't seem to keep from trying to make JavaScript be like another language. The Mochikit guys want JavaScript to be Python, countless programmers have tried to make JavaScript like Java [11], and Prototype tries to make it like Ruby. Prototype makes extensions to the core of JavaScript that can (if you choose to use them) have a dramatic effect on your approach to coding JavaScript. Depending on your background and the way your brain works, this may or may not be of help to you.

OO the Ruby(ish) way: Class.create and Object.extend

The Class.create method allows you to define classes in a more Ruby-like way, although this is purely aesthetic as it essentially just calls the initialize method you define as the constructor, rather than the taking the traditional JavaScript approach of creating objects with constructor functions.

var DOMTable = Class.create();
DOMTable.prototype = {
 initialize : function(el) {
   this.el = el;
 },
 ...
}

However, much more powerful is the stupidly simple but effective Object.extend method. All it does is copy one object's properties and methods to another object, but its uses are many. Here's a quick taster:

// make a (shallow) copy of obj1
var obj2 = Object.extend({}, obj1);

var options = {
 method : "post",
 args : ""
};

// merges in the given options object to the default options object
Object.extend(options, {
 args : "data=454",
 onComplete : function() { alert("done!"); }
});

options.method // "post"
options.args // "ata=454"
options.onComplete // function() { alert("done!"); }

It's most commonly used to "mix in" methods from one object with another. For instance, you could create a set of functions that make certain DOM elements sortable:

var Sortable = {
 sortBy : function(func) {
   ...
 },
 sortByReversed : function(func) {
   ...
 },
 reset : function() {
   ...
 }
};

Then, if we wanted to make our DOMTable from above sortable, we could mix in these methods to the DOMTable object:

var myTable = new DOMTable("table-id");
Object.extend(myTable, Sortable);

Now we can call those methods on the table:

// sort the table using the given function
myTable.sortBy(function (itemA, itemB) { ... });

Function Binding

Prototype also adds to the Function object two really useful methods: bind and bindAsEventListener. These are used mainly to bind a function to a particular object so that the this keyword points to that object. This is incredibly useful when you're setting event handler functions. Imagine you try something like this:

var myObject = new Object();
myObject.message = "Hello!";
myObject.eventHandler = function() {
 alert(this.message);
}

$("mydiv").onmouseover = myObject.eventHandler;

Traditionally, you'd get an error because, when the event triggers the handler function, this refers to the mydiv element, not myObject, so this.message is undefined. You can solve this problem using the bind method like so:

$("mydiv").onmouseover = myObject.eventHandler.bind(myObject);

Now it all works fine, because the this keyword is bound to myObject. Further to that, bindAsEventListener does that same thing, though it passes the event object through to your function in a cross-browser compatible way, so you no longer need to worry about window.event in IE. [12] Try this:

myObject.eventHandler = function(event) {
 alert(event.srcElement.nodeName);
}

$("mydiv").onmouseover = myObject.eventHandler.bindAsEventListener(myObject);

Now our eventHandler function has access to the event object. Much more detail on these two methods is available at their creator's site [13].

New String and Number Methods

Prototype has added an enormous number of useful methods to the built in String object. Let's have a quick look at some of the best.

// "backgroundColor"
"background-color".camelize()

camelize turns hyphenated strings to camel case strings that you can use to work with CSS properties.

// "I am a piece of HTML"
"I am a piece of <strong>HTML</strong>".striptTags()

// {a : 10, b: "thing"}
"a=10&b=thing".toQueryParams()

Prototype adds a great method to Number, too. Say goodbye to your for loops!

// alerts "1", "2", "3" ... "50"
50.times(function(n) {
 alert(n);  
}};

Here, the times method takes a function that will be called the given number of times, and passes in the current iteration number as an argument. This use of an iterator function is common when using Enumerable, which we'll discuss next.

Iterating the Ruby way: Enumerable and Hash

One of the hidden gems of Prototype is the Enumerable mix-in and the Hash object, which have been poached straight out of Ruby. If you're not familiar with Ruby, don't worry. I'll explain it all here.

We'll start with Enumerable. In short, when we add Enumerable to an object using Object.extend, it gives the object in question lots of really useful functions for working with its properties. Enumerable has been added to Array's prototype, so any array has these new methods. Here are a few examples of what you can do with the new "enumerated" arrays [14]:

// alerts "a is at 0" then "b is at 1" then "c is at 2"
["a", "b", "c"].each(function(item, index) {
 alert(item + " is at " + index);
});

// [80,50]
[1, 80, 3, 50].select(function(item) {
 return (item > 20);
});

select creates a new array that contains only the elements that make the function return true.

// ["A", "B", "C"]
["a", "b", "c"].invoke("toUpperCase");

invoke calls the specified method of each element of the array and returns the resulting array.

// ["cat", "rat"]
["cat", "dog", "rat", "mouse",].grep(/at/);

grep returns all elements that match the given regular expression.

Enumerable offers a large number of incredibly powerful functions that can make many tedious DOM scripting tasks a breeze. I strongly suggest you have a good look at the Enumerable methods in \">Sergio Pereira's extremely useful developer notes [15].

There's a small problem here, though. In JavaScript, you can come across many types of objects that, to all intents and purposes, act like arrays but aren't Array objects. Objects such as DOM NodeLists and function arguments won't have Enumerable available to them automatically. This is easy to rectify, though; to add the Enumerable functions to any array-like object, use $A:

// add Enumerable to childNodes
var children = $A($("mydiv").childNodes);

// sets class="highlighted" for all child nodes of "mydiv"
children.each(function(child) {
 child.setAttribute("class", "highlighted");
});

To create a hash, call the magic function $H on any object. This turns all the properties of the object into a set of key-value pairs with Enumerable mixed in. Let's take hashes for a spin:

// create a hash by feeding an object to $H
var contact = $H({
 name : "Dan Webb",
 email : "dan@danwebb.net",
 address : "None of your Business, London",
 postcode : "a111111"
});

// ["name", "email", "address", "postcode"]
contact.keys()
// ["Dan Webb", "dan@danwebb.net","None of your Business, London", "a111111"]
contact.values()
// "name=Dan Webb&email=..."
contact.toQueryString()

Hash extends Enumerable as well, so all those useful methods are also available...

// alerts "name contains Dan Webb" and so on
contact.each(function(item) {
 alert(item.key + " contains " + item.value);
});

At first, if you're not a Rubyist, Enumerable and Hash may seem a bit of a hassle but I can assure you, once you start using them, you'll wonder why you ever bothered getting RSI writing all those for loops! When you use one or more of them together, you'll realise the massive power of these new methods. You can \">read about Enumerable and Hash in more detail [16] at Encyte Media.

The Event object helps to provide what, to many, is the holy grail of JavaScript: simple, cross-browser event handling:

function eventHandlerFunction(e) {
 // the element that triggered the event
 var element = Event.element(e);
 // gets the mouse position
 var mouseX = Event.pointerX(e),
     mouseY = Event.pointerY(e);
 // stop default behaviour and event propagation
 Event.stop(e);
}

// register eventHandlerFunction to the onclick of myObject
Event.observe(myObject, "click", eventHandlerFunction, false);

// removes the event handler
Event.stopObserving(myObject, "click", eventHandlerFunction, false);

In a rather pleasant way, Prototype tries to avoid those pesky memory leaks in IE by automatically removing every observer when the page unloads.

In my opinion, though, this is a rather under-developed event handling solution at the moment, so it might be worth considering using something a bit richer like Dean Edwards's addEvent [17] for the time being.

Handling Forms

The Form and Field objects provide a number of simple but convenient functions for working with forms and input fields, as well as code that supports Prototype's AJAX implementation.

The Form Object

Generally, methods of the Form object take either an ID or an object reference to an element:

// disables the form making all elements read only
Form.disable(form)
// enables a form again
Form.enable(form)
// clears values from all form elements  
Form.reset(form)
// returns an array of all form fields in the form
Form.getElements(form)
// focuses on the first form field
Form.focusFirstElement(form)

The Field Object

The Field object deals with individual form elements, and its methods typically take an ID or an object reference to the element in a similar way to the Form object:

// clears the field, will accept any number of arguments
Field.clear(field)
// returns true if all given fields have a value
Field.clear(field, anotherField)
// gives focus to the field
Field.focus(field)
// selects any text in the field
Field.select(field)

Form Serialisation

In Prototype terms, serializing a form means reading all the form's elements and turning them into a URL-encoded string (nearly) identical to the one that would be sent if you submitted the form. For example, consider this form:

<form id="search" action="search.php [18]" method="post">
 <input type="text" name="query" value="thing" />
 <select name="field">
   <option value="artistname">Artist Name</option>
   <option value="title" selected="selected">Title</option>
 </select>
 <input type="submit" name="submit" value="Search" />
</form>

// query=thing&field=title&submit=Search
Form.serialize($("search"))

Notice that Form.serialize cleverly smoothes over the differences between the ways in which different form elements are accessed, so that inputs, selects, checkboxes and radio buttons are handled properly. Form.serialize is useful for several tasks, but comes into its own when we're working with AJAX, as we'll see shortly.

Form.serialize exhibits some strange behaviour that's worth mentioning here. You'll remember that I said the URL-encoded string that Form.serialize produces is nearly identical to the one that would be sent if you submitted the form. Well, it's "nearly identical" because Form.serialize doesn't deal with submit button or image inputs properly. It includes all submit buttons in the string, regardless of whether or not they've been pressed, and completely ignores image and button inputs. As long as you're aware of this, you can code around it.

Form Observers

Form.Observer and Form.Element.Observer allow you to watch a form (or, in the latter case, a single form element) and trigger callbacks when the data changes. There are actually two flavours of each observer that check for value changes. The first is a periodic observer, which works like this:

new Form.Observer($("myform"), 1, myCallBackFunction);
new Form.Element.Observer($("myfield"), 1, myCallBackFunction);

These observers check every second whether or not the data has changed and, if it has, will call myCallBackFunction.

The second type of observer is event-based and will only perform the check when change or click events are produced for the elements. You can use it like this:

new Form.EventObserver($("myform"), myCallBackFunction);
new Form.Element.EventObserver($("myfield", myCallbackFunction);

If all the fields in the form you're observing support an event handler, this is a much more efficient way to observe the form. However, if you want to watch for changes in elements that don't support these events, use the periodic observers.

Working the DOM

Prototype has 4 objects (Element, Insertion, Observer, and Position) that allow various forms of DOM manipulation and smooth over many of the browser differences that make dealing with the DOM so screen-smashingly infuriating. Instead of throwing your computer out the window, have a look through this section.

The Element Object

The Element object works in the way you've probably come to expect by this point: most of Element's methods simply take an ID or an object reference to the element you want to manipulate. Here's a peek at some of the most useful methods:

// Hides an element
Element.hide(element)
// Shows an element
Element.show(element)
// Adds a CSS class to the element
Element.addClassName(element, "cssClassName")
// Removes a CSS class from the element
Element.removeClassName(element, "cssClassName")
// Returns true if element has the CSS class
Element.hasClassName(element, "cssClassName")
// {width: 394, height: 20}
Element.getDimensions(element)
// replaces the innerHTML of element with newHtml
Element.update(element, newHtml)

See the full list at Sergio Pereira's site [19].

The Insertion Object

I know what you're thinking: this sounds a bit weird, right? Well, the Insertion object adds chunks of HTML in and around an element. There are 4 types of insertion: Before, After, Top and Bottom. Here's how you'd add some HTML before an element with the ID "myelement":

new Insertion.Before("myelement", "<p>I'm before!</p>");

This diagram shows where each type of Insertion will drop your HTML content in relation to the given element.

1514_insertions

The Position Object

The Position object offers a load of methods that can tell you about a given location on the screen, and provide information about that location relative to other elements, in a cross-browser compatible way. This should take much of the fiddliness out of writing animations, effects and drag-and-drop code. Have a look at the Position reference [20] for more details.

Get your Web 2.0 On

"Finally!" you're thinking, "He's got on to what we really want to know about." Yes, I've left it to the end to get into Prototype's AJAX helpers, because they're built on top of all the other stuff we've been going through, and it helps to understand Prototype's form serialization, observers and insertions when we talk about AJAX.

AJAX, in case you've been buried in a very deep hole for the past couple of years, refers to using the browser's XMLHttpRequest object (or equivalent) to communicate with the server without reloading the page. Prototype smoothes over most of the detail, but it's still good to get a bit of background on XMLHttpRequest, which you'll find in this article by Cameron Adams [21].

So, now you're all pumped to get some Web 2.0 action, let's look in to a really simple AJAX request:

new Ajax.Request("hello.php", {
 onSuccess : function(resp) {
   alert("The response from the server is: " + resp.responseText);
 },
 onFailure : function(resp) {
   alert("Oops, there's been an error.");
 },
 parameters : "name=Fred"
});

The Ajax.Request constructor takes a URL and an options object. In this case, we're sending a parameter (name) to hello.php, and alerting its response (or alerting an error if it doesn't work). It's worth taking the time to get familiar with what options are available; here's an overview of the options, along with their defaults:

1514_options

Prototype adds a custom HTTP header to all its AJAX requests so that your server application can detect that it's an AJAX call, rather than a normal call. The header is:

X-Requested-With: XMLHttpRequest

Here's an example PHP function used to detect an AJAX call:

function isAjax() {
 return isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
     $_SERVER ['HTTP_X_REQUESTED_WITH']  == 'XMLHttpRequest';
}

Using this approach, you can write AJAX applications that work even if the user is using an old browser or has JavaScript disabled, but that's a whole other article...

Using Form.serialize to Pass Data to Ajax.Request

As we've seen above, the parameters option is used to pass a URL-encoded string of variables. If the data you need to send is set by a form, as it is with most AJAX applications, you can simply use Form.serialize to generate a URL-encoded string from all of your form fields and pass that into the parameters option like so:

function addComment(e) {
 // submit the form using Ajax
 new Ajax.Request("comment.php", {
   parameters : Form.serialize(this),
   onSuccess : updateComment
 });
 Event.stop(e);
}

Event.observe($("commentform"), "submit", addComment, false);

Writing AJAX Event Handlers

In the example above, onSuccess and onFailure are two examples of AJAX event handlers. Event handler functions given in the options object of an Ajax.Request call are given one argument, which is the XMLHttpRequest object for that AJAX call. I normally call this argument response or resp. You can use this argument to get the response from the server like so:

function successHandler(resp, jsonObj) {
 // returns the response from the server as raw text
 resp.responseText
 // returns the response as an
XML [22] document that you can navigate with the DOM
 resp.responseXML
 // alert some property of the returned JSON
 alert(jsonObj.name);
}

Remember, though, that resp is just the XMLHttpRequest object, so all of those properties are available.

You can send data as JSON [23] from your server by adding the JSON data to the X-JSON response header. This will then automatically be evaluated by Prototype, and sent as the second argument.

The Ajax.Updater and Ajax.PeriodicalUpdater

Many AJAX operations simply involve updating some HTML on your page with HTML returned from the server. The Ajax.Updater object wraps Ajax.Request and simplifies this common use case for us. Here's a simple example:

new Ajax.Updater("mydiv", "hello.php", {
 parameters : "name=Fred",
 onFailure : function(resp) {
   alert("Oops, there's been an error.");
 }
});

The above snippet would simply replace the contents of the element whose ID was "mydiv" with whatever content was returned from the server. Ajax.PeriodicalUpdater is similar, but makes the Ajax call repeatedly at an interval that you set:

new Ajax.PeriodicalUpdater("mydiv", "hello.php", {
 // initial number of seconds interval between calls
 frequency : 1,
 decay : 2
});

The decay option allows you to give your server a bit of a break if it's returning a lot of identical responses. Essentially, every time PeriodicalUpdater makes a request, it compares the results with what the server returned last time. If the values are the same, it multiplies the interval by the decay value. So, for the above example, it would make the next request two seconds later, then four seconds later, and so on, until it received a different result from the server. At that point, the interval would be reset to one second.

AJAX with Responders

AJAX responders allow you to register global event handlers that are triggered for each and every AJAX request that happens on the page. They're very useful for managing applications with large amounts of AJAX activity. For instance, you can use them to show a standard loading animation whenever an AJAX request is happening:

Ajax.Responders.register({
 onCreate : showLoader,
 onComplete : hideLoader
});

If you are looking for some working examples of AJAX with Prototype, try this article [24].

Where to Next?

As we've seen through this article, Prototype not only is useful on its own, but provides an excellent starting point for writing other, more specialized libraries. That's exactly what a growing number of people have been doing.

Script.aculo.us and Moo.fx

Thomas Fuchs' script.aculo.us [25] is getting a lot of attention at the moment for its whiz-bang effects and clever UI [26] widgets. It was originally part of the core Prototype library, but soon grew out of control and broke free of its parent.

Using Prototype as a basis, script.aculo.us specialises in providing a rich user experience through animated effects, simple to use drag and drop functionality, and powerful UI components. There's a nice Wiki on the site, with a rapidly growing store of quality documentation to help you get started, and examples pages to get your creative juices flowing. As script.aculo.us is getting rather large in file size, it's been split into several files, so your users won't have to download the whole library just so you can use a few slide effects. However, even the individual files are pretty bulky.

If you're after some simple effects, I'd really recommend Moo.fx [27]. It's only 3k in size, and gives you some toggling slide and fade effects that, often, are all that's required in a simple AJAX application. It's also a great starting point if you want to write your own effects. Have a look at the code to see a great example of programming using Prototype's Object.extend to provide simple inheritance. Valerio is obviously very focused on keeping his script file sizes down, so he even has a 'lite' version of Prototype (chopped to around 10k), and a lean version of Ajax.Request [28], which I find myself using more often than the full Prototype library. It's definitely worth a look.

Behaviour

Behaviour [29] is a great addition to your DOM scripting toolkit that allows you to use CSS selectors to add behaviour to your documents. Here's a sample of what it allows you to do:

Behaviour.register({
 "#comment_form form" : function(el) {
   // catch form submission and complete with XHR if possible
   el.onsubmit = function() {
     Form.disable(this);
     new Ajax.Request(this.action, {
       method: this.method,
       postBody: Form.serialize(this),
       onComplete: updateComments});
     return false;
   };
 }
});

Read more about this over at the Behaviour site [30]. It's now possible to achieve a similar type of thing using the brand new $$ function discussed earlier, so this may eventually become redundant.

jQuery

jQuery [31] is a compact little library that plays well with Prototype and creates a superhero version of the $ function that can take XPath and CSS 3 selectors. It couples that capability with some extremely clever method chaining approach that makes for very concise code. Watch out for this one.

Wrap up

Prototype is a powerful piece of kit when it comes to adding some DOM scripted spice to your web applications. Unfortunately, its capabilities and tools have grown at a much faster rate than its documentation! We've managed to cover every corner of Prototype in this article, but not every method. I hope, though, that you now know where to go to get the extra information you need.

If you want to know more try Ronnie Roller's prototypedoc.com [32], a resource that keeps up with the growing body of Prototype documentation. Have fun!

Back to SitePoint.com

[1] /glossary.php?q=J#term_9
[2] http://prototype.conio.net
[3] /glossary.php?q=D#term_39
[4] /glossary.php?q=%23#term_72
[5] /glossary.php?q=A#term_73
[6] http://prototype.conio.net
[7] http://prototype.conio.net
[8] /glossary.php?q=C#term_8
[9] http://dev.rubyonrails.org/browser/spinoffs/prototype/
[10] http://mochikit.com
[11] /glossary.php?q=J#term_65
[12] /glossary.php?q=I#term_30
[13] http://www.brockman.se/writing/method-references.html.utf8
[14] /glossary.php?q=%23#term_72
[15] http://www.sergiopereira.com/articles/prototype.js.html#Reference.Enumerable

[16] http://encytemedia.com/blog/articles/2005/12/07/prototype-meets-ruby-a-look-at-enumerable-array-and-hash

[17] http://dean.edwards.name/my/events.js
[18] /glossary.php?q=P#term_1
[19] http://www.sergiopereira.com/articles/prototype.js.html#Element
[20] http://www.sergiopereira.com/articles/prototype.js.html#Position
[21] http://www.sitepoint.com/article/remote-scripting-ajax
[22] /glossary.php?q=X#term_3
[23] http://www.crockford.com/JSON/
[24] http://24ways.org/advent/easy-ajax-with-prototype
[25] http://script.aculo.us/
[26] /glossary.php?q=U#term_67
[27] http://moofx.mad4milk.net/
[28] http://www.mad4milk.net/entry/moo.ajax
[29] http://bennolan.com/behaviour/
[30] http://bennolan.com/behaviour/
[31] http://jquery.com
[32] http://www.prototypedoc.com/

» Page 1

SitePoint Kits

The Search Engine Marketing Kit
The Search Engine Marketing Kit

Proven methods to increase your Traffic!

Download Sample Chapter
The Web Design Business Kit
The Web Design Business Kit

Winning strategies to increase your Income!

Download Sample Chapters

NEW! - September 2006

Book:The Photoshop AnthologyThe Photoshop Anthology: 101 Web Design Tips, Tricks & Techniques

At last a Photoshop CS2 book that takes Web design seriously!

Download the FREE sample chapters

NEW! - July 2006

Book: Deliver First Class Web Sites: 101 Essential Checklists

The ultimate roadmap for web developers, project managers, and anyone involved in the process of building web sites.

Download the FREE sample chapters

NEW! - November 2006

Book: Build Your Own ASP.NET 2.0 Web Site Using C# & VB, 2nd EditionBuild Your Own ASP.NET 2.0 Web Site Using C# & VB, 2nd Edition

Tap the Power and Speed of Microsoft’s Next Generation Framework -- ASP.NET 2.0

Download the FREE sample chapters

'DHTML' 카테고리의 다른 글

[link] 실전 웹 표준 가이드  (0) 2007.04.23
[링크] dhtml grid control  (0) 2007.01.25
Firebug !!!  (0) 2006.12.21
이미지 없이 둥근 모서리 박스 만드는 소스  (0) 2006.11.02
http://www.codingforums.com/  (0) 2006.01.26
Posted by tornado
|

좋습니다~


하지만~~~ 익스 특정 버전에서 div background-image 가 100% 가 안되서 자바스크립트로 살짝 고쳐주던가, explorer hack 를 알아내야 한다는거~


http://www.pjhyett.com/posts/190-the-lightbox-effect-without-lightbox

Posted by tornado
|

Firebug !!!

DHTML 2006. 12. 21. 17:03

'DHTML' 카테고리의 다른 글

[링크] dhtml grid control  (0) 2007.01.25
Painless JavaScript Using Prototype  (0) 2007.01.19
이미지 없이 둥근 모서리 박스 만드는 소스  (0) 2006.11.02
http://www.codingforums.com/  (0) 2006.01.26
드뎌 나왔군... Ajax in action  (0) 2005.10.17
Posted by tornado
|