블로그 이미지
Sunny's

calendar

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 31

Notice

2010. 9. 3. 14:28 JQUERY

Create Vimeo-like top navigation

vimeo

I really like the top navigation implemented on Vimeo.com. First time I saw it I wanted to recreate it. And this is exactly what I am going to do in this tutorial.

What I like the most is the menu that drops down when you hover search box. It offers you different search options that you can choose and narrow your search.

Download source View demo

The base for this tutorial is simple CSS drop down menu based on unordered list. The structure is visually described in the image below:

sample1

As you can see we have UL with four items. The first one is logo with short submenu. Then comes login link, Help link with submenu and search item with submenu. Each submenu is being shown when hover corresponding link.

So this is the base structure that we’ll use here:

<ul id="menu">
    <li class="logo">
        <img style="float:left;" alt="" src="menu_left.png"/>
        <ul id="main">
            <li>Welcome to <b>Create Vimeo-like top navigation</b> tutorial!</li>
        </ul>
    </li>
    <li><a href="#">Login</a>
    </li>
    <li><a href="#">Help</a>
        <ul id="help">
            <li><a href="#">General help</a></li>
            <li><a href="#">Posts</a></li>
            <li><a href="#">Pages</a></li>
        </ul>
    </li>
    <li class="searchContainer">
        <div>
        <input type="text" id="searchField" />
        <img src="magnifier.png" alt="Search" onclick="alert('You clicked on search button')" /></div>
        <ul id="search">
            <li><input id="cbxAll" type="checkbox" />All</li>
            <li><input id="Articles" type="checkbox" />Articles</li>
            <li><input id="Tutorials" type="checkbox" />Tutorials</li>
            <li><input id="Reviews" type="checkbox" />Reviews</li>
            <li><input id="Resources" type="checkbox" />Resources</li>
        </ul>
    </li>
</ul>
<img style="float:left;" alt="" src="menu_right.png"/>

And CSS styles:

/* menu */
#menu{ margin:0px; padding:0px; list-style:none; color:#fff; line-height:45px; display:inline-block;
    float:left; z-index:1000; }
#menu a { color:#fff; text-decoration:none; }
#menu > li {background:#172322 none repeat scroll 0 0; cursor:pointer; float:left; position:relative;
    padding:0px 10px;}
#menu > li a:hover {color:#B0D730;}
#menu .logo {background:transparent none repeat scroll 0% 0%; padding:0px;
    background-color:Transparent;}
/* sub-menus*/
#menu ul { padding:0px; margin:0px; display:block; display:inline;}
#menu li ul { position:absolute; left:-10px; top:0px; margin-top:45px; width:150px; line-height:16px;
    background-color:#172322; color:#0395CC; /* for IE */ display:none; }
#menu li:hover ul { display:block;}
#menu li ul li{ display:block; margin:5px 20px; padding: 5px 0px;  border-top: dotted 1px #606060;
    list-style-type:none; }
#menu li ul li:first-child { border-top: none; }
#menu li ul li a { display:block; color:#0395CC; }
#menu li ul li a:hover { color:#7FCDFE; }
/* main submenu */
#menu #main { left:0px; top:-20px; padding-top:20px; background-color:#7cb7e3; color:#fff;
    z-index:999;}
/* search */
.searchContainer div { background-color:#fff; display:inline; padding:5px;}
.searchContainer input[type="text"] {border:none;}
.searchContainer img { vertical-align:middle;}

But as you can see this is far away from the good looking Vimeo navigation. It is functional, of course, but we need that pretty rounded corners everywhere. The solution is actually simple and it is described in the image below:

sample2

Now that looks fine. What we actually did can be seen in the code below. Let’s take Help submenu for the example:

<li><a href="#">Help</a>
    <ul id="help">
        <li>
            <img class="corner_inset_left" alt="" src="corner_inset_left.png"/>
            <a href="#">General help</a>
            <img class="corner_inset_right" alt="" src="corner_inset_right.png"/>
        </li>
        <li><a href="#">Posts</a></li>
        <li><a href="#">Pages</a></li>
        <li class="last">
            <img class="corner_left" alt="" src="corner_left.png"/>
            <img class="middle" alt="" src="dot.gif"/>
            <img class="corner_right" alt="" src="corner_right.png"/>
        </li>
    </ul>
</li>

We added two absolutely positioned images inside the first LI that will create “shoulders”. Also, we added one more LI to the end of the list that contains two absolutely positioned corners and one 1x1px stretched image to fill the empty space. And this is the additional styles that you need:

/* corners*/
#menu .corner_inset_left { position:absolute; top:0px; left:-12px;}
#menu .corner_inset_right { position:absolute; top:0px; left:150px;}
#menu .last { background:transparent none repeat scroll 0% 0%; margin:0px; padding:0px;
    border:none; position:relative; border:none; height:0px;}
#menu .corner_left { position:absolute; left:0px; top:0px;}
#menu .corner_right { position:absolute; left:132px; top:0px;}
#menu .middle { position:absolute; left:18px; height: 20px; width: 115px; top:0px;}

Now we have functional AND good looking top navigation. This might be optimized, so if you have free time or you need it for your projects, step on it. Or you can use this one as is :)

Did you implement something similar in any project? Do you find this one useful for some of your future projects?

posted by Sunny's
2010. 7. 5. 15:55 JQUERY

One of the biggest concerns I've heard mentioned from users of the Prototype library about jQuery is the lack of support for various array methods. The robust features Prototype provides for arrays is of great benefit to developers that do a lot of array manipulation in their JavaScript.

However, I find that after moving to jQuery, I do less array manipulation than I had done with Prototype. Perhaps jQuery has altered my development pattern so I no longer need array manipulation, or perhaps I have shifted most of my data manipulation to the server. Whatever the case, I have only on occasion missed the Prototype array methods.

While there is some overlap in the ways that jQuery and Prototype handle array manipulation, jQuery does a few things Prototype doesn't do, and Prototype does a number of things that jQuery doesn't. I began writing an article about these differences, but soon got side-tracked writing a jQuery plugin to mimic the array methods Prototype provides.

You can find the plugin at http://code.google.com/p/jquery-protify-js/

With this plugin, you can give a particular array all of the methods that Prototype adds to their Array and Enumerable objects. You can use the methods two different ways. The first does not extend the original array:

JavaScript:
  1. var arr = [1,2,3,4,5,6];
  2. var protArray = $.protify(arr);

This will return an array extended with the Prototype library's methods, but leave the original array untouched.

The second extends the original array by passing in true as the second parameter:

JavaScript:
  1. var arr = [1,2,3,4,5,6];
  2. $.protify(arr, true);

In either case, the JavaScript Array prototype is untouched. When you create new arrays, it will not have the new methods. This way of writing code adds the new methods when they are needed while leaving the underlying JavaScript prototypes untouched. The return value of the methods is an array with the extended methods so that they can be chained.

JavaScript:
  1. var arr = [1,null,2,3,4,5,6];
  2. var arr2 = $.protify(arr)
  3.               .compact()
  4.               .findAll(function(a) {
  5.                 return a>=3;
  6.               })
  7.               .first();  // 3

The above code first returns the arr array values in a new array with the Prototype methods, removes any null/undefined values (using compact), finds all the values in the array greater than or equal to 3 and returns an extended array of them (using findAll), and finally returns the first value of that array (using first). It does all of this without touching the prototype for all arrays.

Here are some useful Prototype array methods included in the plugin:

all()

returns true if every member of the array == true and returns false if even one member != true.

JavaScript:
  1. var arr = [1,2,3,4,5,6];
  2. $.protify(arr, true);
  3. arr.all();  // true

any()

returns true if even one member of the array == true and returns false if every member != true.

JavaScript:
  1. var arr = $.protify([1,2,3,4,5,6]);
  2. arr.any(); // true

map()

similiar to jQuery's $.map. It executes the function passed in on every of member of the array and returns an array of the results.

JavaScript:
  1. $.protify([1,2,3,4,5,6]).map(function(n) {
  2.   return n * 2;
  3. });  //  [2,4,6,8,10,12]

eachSlice(number)

slices the array into an array of arrays of the size passed in. There is an optional second parameter which is a function that acts on each array partition before placing it in the slice.

JavaScript:
  1. var arr = [1,2,3,4,5,6];
  2. $.protify(arr, true);
  3. arr.eachSlice(2);  // [[1,2],[3,4],[5,6]]
  4. arr.eachSlice(2, function (n) {
  5.   return n.map(function(item) {
  6.     return item * 2;
  7.   });
  8. }); // [[2,4],[6,8],[10,12]]

include(value)

returns true if the value is in the array (using == equality).

JavaScript:
  1. var arr = [1,2,3,4,5,6];
  2. $.protify(arr, true);
  3. arr.include(3); // true
  4. arr.include('pie'); // false

max()/min()

returns the maximum/minimum value of the array. Optional parameter is a function that can be used to define the comparison and what gets returned.

JavaScript:
  1. $.protify([{'name': 'frank', 'age': 10},{'name': 'joe', 'age': 12}])
  2.   .max(function(person) { return person.age });
  3. // returns 12

partition()

returns an array with two arrays in it. The first array contains the values that == true in the initial array, and the second all of the values != true. There is an optional parameter that is a function used to do the evaluation.

JavaScript:
  1. $.protify([1,2,3,4,5,6]).partition(function (n) {
  2.   return n <= 3;
  3. });
  4. // [[1,2,3],[4,5,6]]


pluck()

And finally, my favorite. The pluck() method iterates through every member of the array and returns an array of the value of the attribute name passed in.

JavaScript:
  1. var arr = [{'name': 'Frank', 'age': 10}, {'name': 'Joe', 'age': 12}];
  2. $.protify(arr).pluck('age'); // [10, 12]
  3. $.protify(arr).pluck('name'); // ['Frank, 'Joe']

For a full listing and description of all the methods, see the Prototype documentation on arrays and enumerables.

Arrays: http://prototypejs.org/api/array

Enumerables: http://prototypejs.org/api/enumerable

The toJSON method has not yet been implemented because it depends on object methods that Prototype provides. Can you guess what my next project is?

posted by Sunny's
2010. 7. 5. 15:42 JQUERY


Event delegation, as described in the first article of this series, is a way to take advantage of event bubbling to avoid binding an event listener more than once. jQuery 1.3 and the upcoming jQuery 1.4 have many features that make using event delegation in your web pages easier. The aim of this tutorial is to help you understand how these new features work.

From traditional event listening to event delegation

Since an event occurring on an element is propagated to all of its ancestors, an event listener can be bound to a single ancestor of numerous elements instead of being bound to all the elements individually.

Consider the following list items:

HTML:
  1. <ul class="myList">
  2.   <li class="red">The first item.</li>
  3.   <li class="green">The second item.</li>
  4.   <li class="yellow">The third item.</li>
  5.   <li class="blue">The fourth item.</li>
  6. </ul>
  7. <p>Class of the last clicked item: <span id="display"> </span>
  8. </p>

If we want to display the class of an item when it is clicked, a traditional event listener in jQuery would be written like this:

JavaScript:
  1. $("li").click( function( event ) {
  2.   $("#display").text(event.target.className);
  3. });

The event object passed to the handler has a target property which corresponds to the element that has been clicked.

The equivalent using event delegation would look like this:

JavaScript:
  1. $("ul").click( function( event ) {
  2.   $("#display").text(event.target.className);
  3. });

  • The first item.
  • The second item.
  • The third item.
  • The fourth item.

Class of the last clicked item: blue

Event delegation has two main advantages:

  1. setting a single event listener instead of multiple ones is obviously faster;
  2. any new element later added to the list will have the same behavior (as demonstrated in Working with Events, Part 1).

This translation to event delegation that we've just made is, however, slightly too simple, since our original aim was to display only the class of the list items. Using the previous snippet, the class of the unordered list itself can be displayed (by clicking to the left of a bullet-point). We thus have to make sure that the target of the click is a <li>.

JavaScript:
  1. $("ul").click( function( event ) {
  2.   if(event.target.nodeName == "LI") {
  3.     $("#display").text(event.target.className);
  4.   }
  5. });

  • The first item.
  • The second item.
  • The third item.
  • The fourth item.

Class of the last clicked item:

Scanning the ancestors of the event.target: the .closest() method

With such a simple document, event delegation is really that easy to achieve. But things can get more complex if the items have children elements:

HTML:
  1. <ul class="myList">
  2.   <li class="red"><b>The <i>first <u>item</u></i></b>.</li>
  3.  
  4.   <li class="green"><b>The <i>second <u>item</u></i></b>.</li>
  5.   <li class="yellow"><b>The <i>third <u>item</u></i></b>.</li>
  6.  
  7.   <li class="blue"><b>The <i>fourth <u>item</u></i></b>.</li>
  8. </ul>
  9.  
  10. <p>Class of the last clicked item: <span id="display"> </span>
  11. </p>

In this case, if the user clicks on one of the words item, the event.target will be a <u>. It is therefore necessary to loop through all of the ancestors of this original target to find the element that is "interesting" for us: the <li>

JavaScript:
  1. $("ul").click( function( event ) {
  2.   var elem = event.target;
  3.   while( elem.nodeName != "LI" && elem.parentNode) {
  4.     elem = elem.parentNode;
  5.   }
  6.   if(elem.nodeName == "LI") {
  7.     $("#display").text(event.target.className);
  8.   }
  9. });

Notice that if the user clicks outside of an <li>, we have to stop looping through the ancestors at some point; in this case when we find the root of the document (which has no parentNode).

jQuery 1.3 introduced the .closest() method, which replaces this loop by a single line of code:

JavaScript:
  1. $("ul").click( function( event ) {
  2.   var $elem = $(event.target).closest("li");
  3.   if($elem.length) {
  4.     $("#display").text($elem.attr("class"));
  5.   }
  6. });

  • The first item.
  • The second item.
  • The third item.
  • The fourth item.

Class of the last clicked item:

The parameter passed to the .closest() method is a CSS selector that will match the first interesting ancestor.

The context parameter

It can be noted that, when the click occurs outside of an <li>, we could stop looping through the ancestors before hitting the document root, but instead as soon as we hit the <ul>. jQuery 1.4 will introduce an optional context parameter to .closest() for this purpose:

JavaScript:
  1. $("ul").click( function( event ) {
  2.   $("#display").text($(event.target).closest("li", this).attr("class"));
  3. });

Here this is the <ul> element to which the event listener has been bound. This optional parameter improves the performance of event delegation as it prevents the wasted resources of searching for an ancestor which cannot exist.

Event delegation in a single line: the .live() method

jQuery 1.3 also introduces .live(), a method which binds the event listener and implicitly calls the .closest() method to determine whether your event handler should be executed or not.

JavaScript:
  1. $("li").live("click", function( event ) {
  2.   $("#display").text(
  3.     $(event.currentTarget).attr("class")
  4.   );
  5. });

Note how different the syntax using the .live() method is. It seems that we have switched back to a traditional event binding. However, a big difference is that the event listener will work for any existing and future element matching our original selector. There is, of course, nothing magic: behind the scenes .live() simply binds the event listener to the document root and filters any event.target using the .closest() method.

A notable difference with the traditional event binding syntax is that we are not using the target property of the event object inside our event handler, but rather the currentTarget. Indeed, the target of the event is possibly a child of one <li>, whereas the currentTarget property refers to the element that has been found by the implicit .closest().

As explained on the Event Object documentation, the currentTarget property is supposed to be the current DOM element within the event bubbling phase, i.e. the element on which the event has been detected by the event listener, which will always be the element on which the event listener was bound. When using .live(), the currentTarget would therefore always be the document root and you would need to use .closest() once again on the original target to find an interesting ancestor.

JavaScript:
  1. $("li").live("click", function( event ) {
  2.   $("#display").text(
  3.     $(event.target).closest("li").attr("class")
  4.   );
  5. });

This kind of code is required with jQuery 1.3, but as of jQuery 1.4, the currentTarget is modified internally and can thus be used to avoid the extra .closest() inside the event handler.

The context parameter

In jQuery 1.3 all live event listeners were effectively bound to the document root. This can hurt the performance of a web page since all events detected by an event listener will trigger the execution of an implicit .closest(), even though the event target might be totally out of interest.

In jQuery 1.4, .live() should be able to bind the event listener to a specific and more focused element of the document by taking advantage of the context of your jQuery object:

JavaScript:
  1. $("li", $("ul")[0]).live("click", function( event ) {
  2.   $("#display").text(
  3.     $(event.currentTarget).attr("class")
  4.   );
  5. });

The context is the second parameter used to build our jQuery object. To be useful for .live() it has to be set as a pure DOM element, hence the [0] after $("ul"). Brandon Aaron has a useful article explaining the context parameter in detail.

Unbind for .live(): the .die() method

Just like .bind() has its .unbind() counterpart that allows for event listeners to be unbound, .live() has its .die() counterpart.

Unlike .bind(), .live() does not allow for namespaced events to be used.

Dealing with events that don't bubble

There are some events for which event delegation is traditionally not possible, simply because they do not bubble. The promise of jQuery 1.4 is nevertheless to make those events compatible with .live(). How this is achieved will be covered in the upcoming fourth part of this tutorial.

Scripts included in this post:

출처 : http://www.learningjquery.com/2009/09/working-with-events-part-3-more-event-delegation-with-jquery?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+LearningJquery+%28Learning+jQuery%29

posted by Sunny's
2010. 7. 5. 11:37 JQUERY

jQuery 사이트에서도 볼 수 있는 내용이지만 한눈에 들어오고 가벼운거 같아 올려봐요 ^^



 


posted by Sunny's
2010. 7. 5. 11:34 JQUERY
jquery.cheatsheet.1.4.png


Future Colors는 발빠르게 jQuery 1.4 버전의 치트 시트를 배포했습니다. 메서드 단위로 API문서와 링크가 걸렸는 HTML과 PDF 버전 그리고 이미지로 제공하는 PNG 버전이 있습니다.
posted by Sunny's
2010. 7. 2. 11:04 JQUERY

Introduction

This article will cover the following elements:

Form Skinning

Frustrated with the form elements inconsistency among different browsers? With these jQuery plugins, you can unified the look and feel of all your form elements.

Form Validation

It's always good to have client side form validation. These jQuery plugin will save your times and works by reusing already made form validation.

Masking

Masking can help to avoid human mistake. I found these plugins are very helpful to guide users and decrease the chances of bad data.

File Uploader

These file uploader transform the orginal input file element into a more robust file uploader that able to upload multiple files and having a progress bar to indicate the upload progress.

Checkbox & Radio Button

Spice it up your checkbox and radio button with these jQuery plugins!

Spin Button & Slider

Spin button can be useful sometimes. The other alternative will be a slider.

Auto Complete

You must have seen the auto complete functionality from Apple.com, google.com and all the major websites. With the following plugins, we, too can implement it in our websites easily.

Calendar & Time picker

The old school method to let user select date and time are using drop down lists (day, month and year). Now, we can use a calendar, timepicker to replace the old way. Since it's picked from calendar, it decreases the chances of invalid date. I like them.

Drop Down Menu (Select Element)

Want to do more with drop down menu? These plugins able to add more capabilities to drop down menu.

Color Picker

If you are building some online tools that involves colours, I guess you will like the following plugins. jQuery based colour pickers!

Textarea

Sometimes, we get really annoyed when we have to type in message in such a small space (a textarea), and we have to scroll up and down, left and right (sometimes) to read the entire message. Say no more to scrolling! Add this autogrow/resizer capability to textarea to avoid that.

Conclusion

All the plugins are implemented using jQuery, there are still heaps of them out there. Of course, you might able to find other good stuff which are not made from jQuery. If you wrote jQuery plugin that enhances form, and you think it's really cool. Drop me a comment, I will add it in.

posted by Sunny's
2010. 6. 30. 10:11 JQUERY

참고 URL : http://www.malsup.com/jquery/form/#ajaxSubmit

The following code controls the HTML form beneath it. It uses ajaxSubmit to submit the form.

// prepare the form when the DOM is ready 
$(document).ready(function() { 
    var options = { 
        target:        '#output2',   // target element(s) to be updated with server response 
        beforeSubmit:  showRequest,  // pre-submit callback 
        success:       showResponse  // post-submit callback 
 
        // other available options: 
        //url:       url         // override for form's 'action' attribute 
        //type:      type        // 'get' or 'post', override for form's 'method' attribute 
        //dataType:  null        // 'xml', 'script', or 'json' (expected server response type) 
        //clearForm: true        // clear all form fields after successful submit 
        //resetForm: true        // reset the form after successful submit 
 
        // $.ajax options can be used here too, for example: 
        //timeout:   3000 
    }; 
 
    // bind to the form's submit event 
    $('#myForm2').submit(function() { 
        // inside event callbacks 'this' is the DOM element so we first 
        // wrap it in a jQuery object and then invoke ajaxSubmit 
        $(this).ajaxSubmit(options); 
 
        // !!! Important !!! 
        // always return false to prevent standard browser submit and page navigation 
        return false
    }); 
}); 
 
// pre-submit callback 
function showRequest(formData, jqForm, options) { 
    // formData is an array; here we use $.param to convert it to a string to display it 
    // but the form plugin does this for you automatically when it submits the data 
    var queryString = $.param(formData); 
 
    // jqForm is a jQuery object encapsulating the form element.  To access the 
    // DOM element for the form do this: 
    // var formElement = jqForm[0]; 
 
    alert('About to submit: \n\n' + queryString); 
 
    // here we could return false to prevent the form from being submitted; 
    // returning anything other than false will allow the form submit to continue 
    return true

 
// post-submit callback 
function showResponse(responseText, statusText, xhr, $form)  { 
    // for normal html responses, the first argument to the success callback 
    // is the XMLHttpRequest object's responseText property 
 
    // if the ajaxSubmit method was passed an Options Object with the dataType 
    // property set to 'xml' then the first argument to the success callback 
    // is the XMLHttpRequest object's responseXML property 
 
    // if the ajaxSubmit method was passed an Options Object with the dataType 
    // property set to 'json' then the first argument to the success callback 
    // is the json data object returned by the server 
 
    alert('status: ' + statusText + '\n\nresponseText: \n' + responseText + 
        '\n\nThe output div should have already been updated with the responseText.'); 


posted by Sunny's
2010. 6. 29. 11:31 JQUERY
posted by Sunny's
2010. 6. 16. 23:54 JQUERY

경량화 된 인기있는 자바스크립트 라이브러 jQuery를 이용하면 복잡한 AJAX 동작과 다이나믹한 HTML 조작을 상당히 쉽고 일관된
코딩스타일로 구현할 수 있습니다. 이제는 ASP.NET플랫폼의 기본 스크립트 라이브러리로 제공되는 jQuery와, 유용한 사용자
인터페이스의 모음인 jQueryUI를 이용해, 다이나믹한 ASP.NET 웹어플리케이션을 개발하는 방법들에 대해 알아봅니다.

 한진수, 넥슨
2010년 Visual C# MVP로 활동 중에 있으며, 아직 신입개발자 딱지를 떼지 못한 새내기 입니다. 생김새와는 달리 저의 지식이
조금이나마 다른분들에게 도움이 될 수 있다면 그것만으로도 충분히 행복을 느끼는 순진한 개발자 입니다.
 

출처 : http://www.techdays.co.kr/2010spring/remix10/session1_4.html
posted by Sunny's
2010. 6. 16. 19:32 JQUERY

Last month I blogged about how Microsoft is starting to make code contributions to jQuery, and about some of the first code contributions we were working on: jQuery Templates and Data Linking support.

Today, we released a prototype of a new jQuery Globalization Plugin that enables you to add globalization support to your JavaScript applications. This plugin includes globalization information for over 350 cultures ranging from Scottish Gaelic, Frisian, Hungarian, Japanese, to Canadian English.  We will be releasing this plugin to the community as open-source.

You can download our prototype for the jQuery Globalization plugin from our Github repository:

http://github.com/nje/jquery-glob

You can also download a set of samples that demonstrate some simple use-cases with it here.

Understanding Globalization

The jQuery Globalization plugin enables you to easily parse and format numbers, currencies, and dates for different cultures in JavaScript. For example, you can use the Globalization plugin to display the proper currency symbol for a culture:

image

You also can use the Globalization plugin to format dates so that the day and month appear in the right order and the day and month names are correctly translated:

image

Notice above how the Arabic year is displayed as 1431. This is because the year has been converted to use the Arabic calendar.

Some cultural differences, such as different currency or different month names, are obvious. Other cultural differences are surprising and subtle. For example, in some cultures, the grouping of numbers is done unevenly. In the "te-IN" culture (Telugu in India), groups have 3 digits and then 2 digits. The number 1000000 (one million) is written as "10,00,000". Some cultures do not group numbers at all. All of these subtle cultural differences are handled by the jQuery Globalization plugin automatically.

Getting dates right can be especially tricky. Different cultures have different calendars such as the Gregorian and UmAlQura calendars. A single culture can even have multiple calendars. For example, the Japanese culture uses both the Gregorian calendar and a Japanese calendar that has eras named after Japanese emperors. The Globalization Plugin includes methods for converting dates between all of these different calendars.

Using Language Tags

The jQuery Globalization plugin uses the language tags defined in the RFC 4646 and RFC 5646 standards to identity cultures (see http://tools.ietf.org/html/rfc5646). A language tag is composed out of one or more subtags separated by hyphens. For example:

Language Tag Language Name (in English)
en-AU English (Australia)
en-BZ English (Belize)
en-CA English (Canada)
Id Indonesian
zh-CHS Chinese (Simplified) Legacy
Zu isiZulu

Notice that a single language, such as English, can have several language tags. Speakers of English in Canada format numbers, currencies, and dates using different conventions than speakers of English in Australia or the United States.  You can find the language tag for a particular culture by using the Language Subtag Lookup tool located here:  http://rishida.net/utils/subtags/

The jQuery Globalization plugin download includes a folder named globinfo that contains the information for each of the 350 cultures. Actually, this folder contains more than 700 files because the folder includes both minified and un-minified versions of each file.

For example, the globinfo folder includes JavaScript files named jQuery.glob.en-AU.js for English Australia, jQuery.glob.id.js for Indonesia, and jQuery.glob.zh-CHS for Chinese (Simplified) Legacy.

Example: Setting a Particular Culture

Imagine that you have been asked to create a German website and want to format all of the dates, currencies, and numbers using German formatting conventions correctly in JavaScript on the client. The HTML for the page might look like this:

image

Notice the span tags above. They mark the areas of the page that we want to format with the Globalization plugin. We want to format the product price, the date the product is available, and the units of the product in stock.

To use the jQuery Globalization plugin, we’ll add three JavaScript files to the page: the jQuery library, the jQuery Globalization plugin, and the culture information for a particular language:

image

In this case, I’ve statically added the jQuery.glob.de-DE.js JavaScript file that contains the culture information for German. The language tag “de-DE” is used for German as spoken in Germany.

Now that I have all of the necessary scripts, I can use the Globalization plugin to format the product price, date available, and units in stock values using the following client-side JavaScript:

image

The jQuery Globalization plugin extends the jQuery library with new methods - including new methods named preferCulture() and format(). The preferCulture() method enables you to set the default culture used by the jQuery Globalization plugin methods. Notice that the preferCulture() method accepts a language tag. The method will find the closest culture that matches the language tag.

The $.format() method is used to actually format the currencies, dates, and numbers. The second parameter passed to the $.format() method is a format specifier. For example, passing “c” causes the value to be formatted as a currency. The ReadMe file at github details the meaning of all of the various format specifiers: http://github.com/nje/jquery-glob

When we open the page in a browser, everything is formatted correctly according to German language conventions. A euro symbol is used for the currency symbol. The date is formatted using German day and month names. Finally, a period instead of a comma is used a number separator:

image

You can see a running example of the above approach with the 3_GermanSite.htm file in this samples download.

Example: Enabling a User to Dynamically Select a Culture

In the previous example we explicitly said that we wanted to globalize in German (by referencing the jQuery.glob.de-DE.js file). Let’s now look at the first of a few examples that demonstrate how to dynamically set the globalization culture to use.

Imagine that you want to display a dropdown list of all of the 350 cultures in a page. When someone selects a culture from the dropdown list, you want all of the dates in the page to be formatted using the selected culture.

image

Here’s the HTML for the page:

image

Notice that all of the dates are contained in a <span> tag with a data-date attribute (data-* attributes are a new feature of HTML 5 that conveniently also still work with older browsers). We’ll format the date represented by the data-date attribute when a user selects a culture from the dropdown list.

In order to display dates for any possible culture, we’ll include the jQuery.glob.all.js file like this:

image

The jQuery Globalization plugin includes a JavaScript file named jQuery.glob.all.js. This file contains globalization information for all of the more than 350 cultures supported by the Globalization plugin.  At 367KB minified, this file is not small. Because of the size of this file, unless you really need to use all of these cultures at the same time, we recommend that you add the individual JavaScript files for particular cultures that you intend to support instead of the combined jQuery.glob.all.js to a page. In the next sample I’ll show how to dynamically load just the language files you need.

Next, we’ll populate the dropdown list with all of the available cultures. We can use the $.cultures property to get all of the loaded cultures:

image

Finally, we’ll write jQuery code that grabs every span element with a data-date attribute and format the date:

image

The jQuery Globalization plugin’s parseDate() method is used to convert a string representation of a date into a JavaScript date. The plugin’s format() method is used to format the date. The “D” format specifier causes the date to be formatted using the long date format.

And now the content will be globalized correctly regardless of which of the 350 languages a user visiting the page selects.  You can see a running example of the above approach with the 4_SelectCulture.htm file in this samples download.

Example: Loading Globalization Files Dynamically

As mentioned in the previous section, you should avoid adding the jQuery.glob.all.js file to a page whenever possible because the file is so large. A better alternative is to load the globalization information that you need dynamically.

For example, imagine that you have created a dropdown list that displays a list of languages:

image

The following jQuery code executes whenever a user selects a new language from the dropdown list. The code checks whether the globalization file associated with the selected language has already been loaded. If the globalization file has not been loaded then the globalization file is loaded dynamically by taking advantage of the jQuery $.getScript() method.

image

The globalizePage() method is called after the requested globalization file has been loaded, and contains the client-side code to perform the globalization.

The advantage of this approach is that it enables you to avoid loading the entire jQuery.glob.all.js file. Instead you only need to load the files that you need and you don’t need to load the files more than once.

The 5_Dynamic.htm file in this samples download demonstrates how to implement this approach.

Example: Setting the User Preferred Language Automatically

Many websites detect a user’s preferred language from their browser settings and automatically use it when globalizing content. A user can set a preferred language for their browser. Then, whenever the user requests a page, this language preference is included in the request in the Accept-Language header.

When using Microsoft Internet Explorer, you can set your preferred language by following these steps:

  1. Select the menu option Tools, Internet Options.
  2. Select the General tab.
  3. Click the Languages button in the Appearance section.
  4. Click the Add button to add a new language to the list of languages.
  5. Move your preferred language to the top of the list.

image

Notice that you can list multiple languages in the Language Preference dialog. All of these languages are sent in the order that you listed them in the Accept-Language header:

Accept-Language: fr-FR,id-ID;q=0.7,en-US;q=0.3

Strangely, you cannot retrieve the value of the Accept-Language header from client JavaScript. Microsoft Internet Explorer and Mozilla Firefox support a bevy of language related properties exposed by the window.navigator object, such as windows.navigator.browserLanguage and window.navigator.language, but these properties represent either the language set for the operating system or the language edition of the browser. These properties don’t enable you to retrieve the language that the user set as his or her preferred language.

The only reliable way to get a user’s preferred language (the value of the Accept-Language header) is to write server code. For example, the following ASP.NET page takes advantage of the server Request.UserLanguages property to assign the user’s preferred language to a client JavaScript variable named acceptLanguage (which then allows you to access the value using client-side JavaScript):

image

In order for this code to work, the culture information associated with the value of acceptLanguage must be included in the page. For example, if someone’s preferred culture is fr-FR (French in France) then you need to include either the jQuery.glob.fr-FR.js or the jQuery.glob.all.js JavaScript file in the page or the culture information won’t be available.  The “6_AcceptLanguages.aspx” sample in this samples download demonstrates how to implement this approach.

If the culture information for the user’s preferred language is not included in the page then the $.preferCulture() method will fall back to using the neutral culture (for example, using jQuery.glob.fr.js instead of jQuery.glob.fr-FR.js). If the neutral culture information is not available then the $.preferCulture() method falls back to the default culture (English).

Example: Using the Globalization Plugin with the jQuery UI DatePicker

One of the goals of the Globalization plugin is to make it easier to build jQuery widgets that can be used with different cultures.

We wanted to make sure that the jQuery Globalization plugin could work with existing jQuery UI plugins such as the DatePicker plugin. To that end, we created a patched version of the DatePicker plugin that can take advantage of the Globalization plugin when rendering a calendar. The following image illustrates what happens when you add the jQuery Globalization and the patched jQuery UI DatePicker plugin to a page and select Indonesian as the preferred culture:

image

Notice that the headers for the days of the week are displayed using Indonesian day name abbreviations. Furthermore, the month names are displayed in Indonesian.

You can download the patched version of the jQuery UI DatePicker from our github website. Or you can use the version included in this samples download and used by the 7_DatePicker.htm sample file.

Summary

I’m excited about our continuing participation in the jQuery community. This Globalization plugin is the third jQuery plugin that we’ve released.

We’ve really appreciated all of the great feedback and design suggestions on the jQuery templating and data-linking prototypes that we released earlier this year.  We also want to thank the jQuery and jQuery UI teams for working with us to create these plugins.

Hope this helps,

Scott

출처 : http://weblogs.asp.net/scottgu/archive/2010/06/10/jquery-globalization-plugin-from-microsoft.aspx

posted by Sunny's
prev 1 2 3 next