50 Fresh jQuery Tutorials 2011

50 Fresh jQuery Tutorials of 2011 that were recently created, so you don’t have to do the search as we did it and will continue to do it to build a useful library of jquery plugins and solutions.

Acesse todos os 50 jQuery: http://webdesign14.com/50-fresh-jquery-tutorials-2011/

Alguns exemplos:

1. Parallax Slider with jQuery

jquery tutorials

View Live Demo

2. Animated Form Switching with jQuery

jquery tutorials

View Live Demo

3. Sweet Thumbnails Preview Gallery

jquery tutorials

View Live Demo

4. How To Create a Cool Animated Menu with jQuery

jquery tutorials

View Live Demo

5. How to Make Auto-Advancing Slideshows

jquery tutorials

View Live Demo

6. Digg Like URL Submitter Using JQuery and PHP

jquery tutorials

View Live Demo

7. Simple JQuery Flickr Style Tooltip Menu

jquery tutorials

View Live Demo

8. Shuffle Between Images Using JQuery

jquery tutorials

View Live Demo

9. JQuery Expand Stacked Images Using Slider

jquery tutorials

View Live Demo

10. Thumbnails Preview Slider with jQuery

 jquery tutorials

View Live Demo

11. jQuery’s Data Method – How and Why to Use It

jquery tutorials

View Live Demo

12. Spotlight: jQuery replaceText

 jquery tutorials

View Live Demo

13. XML banner fader in jQuery
jquery tutorials

View Live Demo

14. Overlay-like Effect with jQuery

jquery tutorials

View Live Demo

15. Fullscreen Gallery with Thumbnail Flip

jquery tutorials

View Live Demo

16. Making a Flickr-powered Slideshow

 jquery tutorials

View Live Demo

17. Converting jQuery Code to a Plugin

jquery tutorials

View Live Demo

18. jQuery draggable captcha

jquery tutorials

View Live Demo

19. Rounded Menu with CSS3 and jQuery

 jquery tutorials

View Live Demo

20. Jquery Advanced Ajax validation with CAPTCHA

 jquery tutorials

View Live Demo

21. Populate Select Boxes

 jquery tutorials

View Live Demo

22. Spotlight: Constrained Stickies with jQuery

jquery tutorials

View Live Demo

23. Fun with jQuery Templating and AJAX
jquery tutorials

View Live Demo

24. Yahoo Instant Search with Jquery and Ajax

jquery tutorials

View Live Demo

25. Gravity Registration Form with Jquery
jquery tutorials

View Live Demo

Acesse todos os 50 jQuery: http://webdesign14.com/50-fresh-jquery-tutorials-2011/

Anúncios

ReadOnly ASP.NET TextBox at RunTime using jQuery

n this short and simple article, we will see how to check a condition and make a TextBox readonly at runtime using jQuery.
This article is a chapter from my EBook called 51 Recipes with jQuery and ASP.NET Controls. The chapter has been modified a little to publish it as an article.
Note that for demonstration purposes, I have included jQuery code in the same page. Ideally, these resources should be created in separate folders for maintainability. The code shown below has been tested on IE7, IE8, Firefox 3, Chrome 2 and Safari 4.
Let us quickly jump to the solution to check if the TextBox has some value in it and make it read-only.
<head id=”Head1″ runat=”server”>
    <title>Make TextBoxes ReadOnly at RunTime</title>
   
    <script type=”text/javascript”
    </script>      
   
    <script type=”text/javascript”>
        $(function ()
        {
            $(‘input:text[value!=]’).each(function ()
            {
                $(this).attr(‘readonly’, true);
            });
        });
    </script>
</head>
<body>
    <form id=”form1″ runat=”server”>
    <div class=”bigDiv”>
        <h2>Make TextBoxes ReadOnly at RunTime</h2><br />
        <asp:TextBox ID=”tb1″ runat=”server” Text=”ReadOnlyText”/><br />
        <asp:TextBox ID=”tb2″ runat=”server” Text=””/><br />
        <asp:TextBox ID=”tb3″ runat=”server” Text=””/><br />
        <asp:TextBox ID=”tb4″ runat=”server” Text=”ReadOnlyText” />
        <br /><br />
        Tip: 1st and 4th TextBoxes have been made read-only
        and cannot be edited
    </div>
    </form>
</body>
</html>
 
This is a very common requirement that most developers face on a daily basis. While editing a form, textboxes that have text in it, should be made read-only. The code shown in the example filters the textboxes that have values in it (tb1 and tb4) and applies the ‘readonly’ attribute to them.
$(‘input:text[value!=]’).each(function() {
     $(this).attr(‘readonly’, true);
});
When the document loads, the user is able to enter text in the second and third textboxes, but not in the first and fourth, since they are now read-only. It is that simple!
TextBox

A jQuery UI Combobox: Under the hood

by Jörn Zaefferer

The jQuery UI 1.8 release brings along the new autocomplete widget. An autocomplete adds a list of suggestions to an input field, displayed and filtered while the user is typing. This could be attached to a search field, suggesting either search terms or just matching results for faster navigation. But what if there is a fixed list of options, usually implemented as a standard HTML select element, where the ability to filter would help users find the right value way faster?

That’s a “combobox.” A combobox works like a select, but also has an input field to filter the options by typing. jQuery UI 1.8 actually provides a sample implementation of a combobox as a demo. In this article, we’ll look under the hood of the combobox demo, to explore both the combobox widget and the autocomplete widget that it uses.

Let’s starts with the initial markup:

HTML:

  1. <label>Your preferred programming language: </label>
  2. <select>
  3.   <option value=”a”>asp</option>
  4.   <option value=”c”>c</option>
  5.   <option value=”cpp”>c++</option>
  6.   <option value=”cf”>coldfusion</option>
  7.   <option value=”g”>groovy</option>
  8.   <option value=”h”>haskell</option>
  9.   <option value=”j”>java</option>
  10.   <option value=”js”>javascript</option>
  11.   <option value=”p1″>perl</option>
  12.   <option value=”p2″>php</option>
  13.   <option value=”p3″>python</option>
  14.   <option value=”r”>ruby</option>
  15.   <option value=”s”>scala</option>
  16. </select>

Nothing special there, just a label and a select element with a few options.

The code to apply the combobox widget to the select is quite simple, too:

JavaScript:

  1. $(“select”).combobox();

Let’s look at the code for this combobox widget. First, the full code, to give you an overview. We’ll dig into the details step-by-step afterwards.

JavaScript:

  1. $.widget(“ui.combobox”, {
  2.   _create: function() {
  3.     var self = this;
  4.     var select = this.element.hide();
  5.     var input = $(“<input />”)
  6.       .insertAfter(select)
  7.       .autocomplete({
  8.         source: function(request, response) {
  9.           var matcher = new RegExp(request.term, “i”);
  10.           response(select.children(“option”).map(function() {
  11.             var text = $(this).text();
  12.             if (this.value && (!request.term || matcher.test(text)))
  13.               return {
  14.                 id: this.value,
  15.                 label: text.replace(new RegExp(“(?![^&;]+;)(?!<[^<>]*)(” + $.ui.autocomplete.escapeRegex(request.term) + “)(?![^<>]*>)(?![^&;]+;)”, “gi”), “<strong>$1</strong>”),
  16.                 value: text
  17.               };
  18.           }));
  19.         },
  20.         delay: 0,
  21.         change: function(event, ui) {
  22.           if (!ui.item) {
  23.             // remove invalid value, as it didn’t match anything
  24.             $(this).val(“”);
  25.             return false;
  26.           }
  27.           select.val(ui.item.id);
  28.           self._trigger(“selected”, event, {
  29.             item: select.find(“[value='” + ui.item.id + “‘]”)
  30.           });
  31.          
  32.         },
  33.         minLength: 0
  34.       })
  35.       .addClass(“ui-widget ui-widget-content ui-corner-left”);
  36.     $(“<button> </button>”)
  37.     .attr(“tabIndex”, -1)
  38.     .attr(“title”, “Show All Items”)
  39.     .insertAfter(input)
  40.     .button({
  41.       icons: {
  42.         primary: “ui-icon-triangle-1-s”
  43.       },
  44.       text: false
  45.     }).removeClass(“ui-corner-all”)
  46.     .addClass(“ui-corner-right ui-button-icon”)
  47.     .click(function() {
  48.       // close if already visible
  49.       if (input.autocomplete(“widget”).is(“:visible”)) {
  50.         input.autocomplete(“close”);
  51.         return;
  52.       }
  53.       // pass empty string as value to search for, displaying all results
  54.       input.autocomplete(“search”, “”);
  55.       input.focus();
  56.     });
  57.   }
  58. });

Let’s break this down, piece by piece:

JavaScript:

  1. $.widget(“ui.combobox”, {
  2.   _create: function() {
  3.     // all the code
  4.   }
  5. });

This defines a new widget, in the ui namespace (don’t use this for your own widgets, it’s reserved for jQuery UI widgets) and adds the only method, _create. This is the constructor method for jQuery UI widgets, and will be called only once. In versions prior to 1.8 it was called _init. The _init method still exists, but it is called each time you call .combobox() (with or without options). Keep in mind that our widget implementation is not complete, as it lacks the destroy method. It’s just a demo.

Coming up next is the creation of an input element and applying the autocomplete to it, with data provided by the select element.

JavaScript:

  1. var self = this;
  2. var select = this.element.hide();
  3. var input = $(“<input />”)
  4.   .autocomplete({
  5.     source: function(request, response) {
  6.       // implements retrieving and filtering data from the select
  7.     },
  8.     delay: 0,
  9.     change: function(event, ui) {
  10.       // implements updating the select with the selection
  11.     },
  12.     minLength: 0
  13.   })
  14.   .addClass(“ui-widget ui-widget-content ui-corner-left”);

It starts with a few variable declarations: var self = this will be used inside callbacks below, where this will refer to something else. The var select references the select element on which the combobox gets applied. To replace the select with the text input, the select is hidden.

Next, an input element is created from scratch, inserted after the select element into the DOM, and transformed into an autocomplete widget. All three autocomplete options are customized:

  • source provides the filtered data to display
  • delay specifies the amount of time to wait for displaying data between each key press, here set to zero as the data is local
  • minLength is set to 0, too, so that a cursor-down or -up key press will display the autocomplete menu, even when nothing was entered.

Let’s break down the source implementation:

JavaScript:

  1. source: function(request, response) {
  2.   var matcher = new RegExp(request.term, “i”);
  3.   response(select.children(“option”).map(function() {
  4.     var text = $(this).text();
  5.     if (this.value && (!request.term || matcher.test(text)))
  6.       return {
  7.         id: this.value,
  8.         label: text.replace(new RegExp(“(?![^&;]+;)(?!<[^<>]*)(” + $.ui.autocomplete.escapeRegex(request.term) + “)(?![^<>]*>)(?![^&;]+;)”, “gi”), “<strong>$1</strong>”),
  9.         value: text
  10.       };
  11.   }));
  12. },

There is a bit of matching and mapping involved here: At first, a regular expression object is defined, based on the entered term. That gets reused in the function below. The response argument, a callback, gets called, to provide the data to display. The argument passed is the result of the call to select.find("option".map(callback). That finds all option elements within our original select, then maps each option to a different object, implemented in another callback passed to the map method.

This callback will return undefined, thereby removing an item, when a search term is present and the text of the option doesn’t match the entered value. Otherwise (no term, or it matches), it’ll return an object with three properties:

  • id: the value attribute of the option, will later be used to update the select element with a new selection
  • label: based on the text of the option, with the matched term highlighted with some regexing (another example of a write-only regular expression)
  • value: the unmodified text of the option, to be inserted into the text input field

The label and value properties are expected by the autocomplete widget, the id property has an arbitrary name, used here only by the combobox widget.

Before, I mentioned that the combobox wideget customizes all three autocomplete options, but there were actually four options specified. The fourth property here, change, is actually an event. This is the implementation:

JavaScript:

  1. change: function(event, ui) {
  2.   if (!ui.item) {
  3.     // remove invalid value, as it didn’t match anything
  4.     $(this).val(“”);
  5.     return false;
  6.   }
  7.   select.val(ui.item.id);
  8.   self._trigger(“selected”, event, {
  9.     item: select.find(“[value='” + ui.item.id + “‘]”)
  10.   });
  11.  
  12. },

The ui.item argument refers to the data we provided in the source option. In case the user entered a value not provided, ui.item is null, which is used here to drop that input, by setting the value of the input element to an empty string. If an item is present, the select is updated to match that item, using ui.item.id, which refers to the value attribute of the associated option element. And, for further customization for someone using the combobox widget, a selected event is triggered.

The next code block creates the button that opens the full list of options:

JavaScript:

  1. $(“<button>&nbsp;</button>”)
  2. .attr(“tabIndex”, -1)
  3. .attr(“title”, “Show All Items”)
  4. .insertAfter(input)
  5. .button({
  6.   icons: {
  7.     primary: “ui-icon-triangle-1-s”
  8.   },
  9.   text: false
  10. }).removeClass(“ui-corner-all”)
  11. .addClass(“ui-corner-right ui-button-icon”)
  12. .click(function() {
  13.   // close if already visible
  14.   if (input.autocomplete(“widget”).is(“:visible”)) {
  15.     input.autocomplete(“close”);
  16.     return;
  17.   }
  18.   // pass empty string as value to search for, displaying all results
  19.   input.autocomplete(“search”, “”);
  20.   input.focus();
  21. });

Another element is created on-the-fly. It gets tabIndex="-1" to take it out of the tab order, as it’s mostly useful for mouse interactions. Keyboard interaction is already covered by the input element. It gets a title attribute to provide a tooltip and is inserted after the input element into the DOM. A call to .button() with some options together with a bit of class-mangling transforms the button into a Button widget that displays a down-arrow icon with rounded corners on the right (the input has rounded-corners on the left).

Finally a click event is bound to the button: If the autocomplete menu is already visible, it gets closed, otherwise the autocomplete’s search method is called with an empty string as the argument, to search for all elements, independent of the current value within the input. As the input handles keyboard input, it gets focused. Having focus on the button would be useless or would require duplicate keyboard interaction that the input already supports.

And that’s it! We can see that the autocomplete widget is flexible enough to allow all this with option customization, events, and calling a few methods. We don’t have to “subclass” autocomplete (creating a new widget with the autocomplete as the parent prototype instead of $.widget). Instead, we can make the combobox independent of any internal or private autocomplete methods. Check out the combobox demo on the jQuery UI site.

Autocomplete Migration Guide

by Jörn Zaefferer

The jQuery Autocomplete plugin got a successor recently, the jQuery UI Autocomplete. In this guide we’ll look at the old plugin API step-by-step, and how to migrate to the new API.

At first it may look like the new plugin supports barely any of the old options. We’ll see how all the old options can be implemented using the three new options and the six events.

The old plugin had two arguments: data or url, and options. Lets start with that data-or-url argument. With the new autocomplete plugin, you’ll just pass the data or url to the source option.

So, with the old plugin you’d have this code:

JavaScript:

  1. $(“input”).autocomplete([“a”, “b”, “c”]);

And that becomes, easy enough:

JavaScript:

  1. $(“input”).autocomplete({
  2.   source: [“a”, “b”, “c”]
  3. });

The same applies if you provided a URL as the first argument, although there is a difference between the two plugins for remote data. The old plugin expected a special format with pipes to separate values and newlines to separate rows. That is gone for good, the Autocomplete widget now works with JSON by default. The simplest form is the same as in the example above, an array of string values.

Instead of an array of strings, the widget also accepts an array of objects, with at least a label or value property, or both, in addition to whatever else you need. More on that can be found in the documentation and various demos, eg. the Custom Data demo shows how to use custom properties and even display them.

Lets look through the rest of the options for the old plugin, and what to do with them for the new plugin:

  • autoFill: Gone with no immediate replacement available, for good reasons: The default behaviour when selecting items via keyboard now puts the focussed value into the input, like the Firefox Awesomebar does it. It’s not the same as what the autoFill option did, but there should be no need to recreate that effect.
  • cacheLength: There is no built-in caching support anymore, but it’s really easy to implement your own, as shown by the Remote with caching demo.
  • delay: Still exists with the same behaviour, but the default is always 300 milliseconds.
  • extraParams: Extra params and all other Ajax related options can be customized by using a callback for the source option. Use $.ajax to send the actual request, with the response callback argument passed to source as the success callback for the $.ajax call. The Remote JSONP datasource demo has an example for that.
  • formatItem, formatMatch, formatResult, highlight: All gone, instead use the source option to either provide the formatted data from your serverside, or implement a custom source to do special formatting. The combobox demo shows how to do that, with a more extensive explanation of that demo right on this site.
  • matchCase, matchContains, matchSubset: All gone, too. The builtin matcher for local data will do a case-insensitive match-contains, everything else has to be implemented on the serverside or using the source option. The combobox linked just above also has an example for that.
  • max: Gone; if your server sends too many items, pass a function for the source option that calls $.ajax and truncates or filters the resulting list.
  • minChars: Still present, but was renamed to minLength. Behaves just the same, even the default is still the same, with minLength: 1.
  • multiple, multipleSeperator: Not built-in anymore, but easy to recreate. There are two demos for this, once with local data, once with remote data.
  • mustMatch: Gone, but easy to implement with the select event. Once more, the combobox provides an example for that.
  • scroll, scrollHeight: These option are gone, but the underlying Menu widget actually has support for scrolling. If you have enough items and specify a height via CSS, the menu will scroll.
  • selectFirst: Similar to autoFill (at the top of this list), this option is gone and has now immediate replacement, nor a need for one. The behaviour for selecting values is solid enough to make this option redundant.
  • width: Gone and not required anymore. The menu will automatically be as wide as the input it completes, or wider, as the content requires. And you can always restrict with width using CSS.

And thats about it. If you’re still looking for a particular replacement, take a look at the various events available, and study the use of the source-option within the various demos. If you still have a question, post on the Using jQuery UI forum. If you spot some mistake or see something that can be improved in this article, please let us know in the comments.

JQuery Autocomplete

Autocomplete é um recurso muito interessante a ser usado em formulários web quando precisamos de um campo que de início seria um dropdownlist, mas, que se torna inviável pelo número de registros a ser carregado. Quem já não se deparou com a situação de ter que carregar mais de 50 u 100 registros em uma dropdownlist?

Segue abaixo um recurso que estamos utilizando bastante em formulários web em nossos desenvolvimentos na fábrica de softwares da DANRESA Consultoria de Informatica e que tem agradado nossos clientes com uma boa experiência de usuário.

Autocomplete

Autocomplete, when added to an input field, enables users to quickly find and select from a pre-populated list of values as they type, leveraging searching and filtering.

By giving an Autocomplete field focus or entering something into it, the plugin starts searching for entries that match and displays a list of values to choose from. By entering more characters, the user can filter down the list to better matches.

This can be used to enter previous selected values, for example you could use Autocomplete for entering tags, to complete an address, you could enter a city name and get the zip code, or maybe enter email addresses from an address book.

You can pull data in from a local and/or a remote source: Local is good for small data sets (like an address book with 50 entries), remote is necessary for big data sets, like a database with hundreds or millions of entries to select from.

Autocomplete can be customized to work with various data sources, by just specifying the source option. A data source can be:

  • an Array with local data
  • a String, specifying a URL
  • a Callback

The local data can be a simple Array of Strings, or it contains Objects for each item in the array, with either a label or value property or both. The label property is displayed in the suggestion menu. The value will be inserted into the input element after the user selected something from the menu. If just one property is specified, it will be used for both, eg. if you provide only value-properties, the value will also be used as the label.

When a String is used, the Autocomplete plugin expects that string to point to a URL resource that will return JSON data. It can be on the same host or on a different one (must provide JSONP). The request parameter “term” gets added to that URL. The data itself can be in the same format as the local data described above.

The third variation, the callback, provides the most flexibility, and can be used to connect any data source to Autocomplete. The callback gets two arguments:

  • A request object, with a single property called “term”, which refers to the value currently in the text input. For example, when the user entered “new yo” in a city field, the Autocomplete term will equal “new yo”.
  • A response callback, which expects a single argument to contain the data to suggest to the user. This data should be filtered based on the provided term, and can be in any of the formats described above for simple local data (String-Array or Object-Array with label/value/both properties).

The demos all focus on different variations of the source-option – look for the one that matches your use case, and take a look at the code.

 Exemplo de Código

Faça um teste em: http://jqueryui.com/demos/autocomplete/#remote-jsonp 

<meta charset="UTF-8" />

<script type="text/javascript">
$(function() {
function log(message) {
$("<div/>").text(message).prependTo("#log");
$("#log").attr("scrollTop", 0);
}

$("#city").autocomplete({
source: function(request, response) {
$.ajax({
url: "http://ws.geonames.org/searchJSON",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function(data) {
response($.map(data.geonames, function(item) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
}
}))
}
})
},
minLength: 2,
select: function(event, ui) {
log(ui.item ? ("Selected: " + ui.item.label) : "Nothing selected, input was " + this.value);
},
open: function() {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function() {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
});
</script>
<style>
.ui-autocomplete-loading { background: url(indicator.gif) no-repeat right; }
#city { width: 25em; }
</style>

<div>

<div>
<label for="city">Your city: </label>
<input id="city" />
Powered by <a href="http://geonames.org">geonames.org</a>
</div>

<div style="margin-top:2em; font-family:Arial">
Result:
<div id="log" style="height: 200px; width: 300px; overflow: auto;"></div>
</div>

</div><!-- End demo -->

<div>
<p>
The Autocomplete widgets provides suggestions while you type into the field. Here the suggestions are cities, displayed when at least two characters are entered into the field.
</p>
<p>
In this case, the datasource is the <a href="http://geonames.org">geonames.org webservice</a>. While only the city name itself ends up in the input after selecting an element, more info is displayed in the suggestions to help find the right entry. That data is also available in callbacks, as illustrated by the Result area below the input.
</p>
</div><!-- End demo-description -->