CDN jquery:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
 
latest version in the 1.6 branch
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
 
per lo sviluppo puntare all'ultima versione disponibile. da non fare per i siti in produzione
<script src="http://code.jquery.com/jquery-latest.js"></script>

data

store data inside the dom

$('selector').data('paramtername', 'data being stored');
// then later getting the data with
$('selector').data('paramtername');

passare dati al client embedded nel dom con l'attributo data-options, che può contenere oggetti

<div id="d1" data-role="page" data-last-value="43" data-hidden="true"
    data-options='{"name":"John"}'>
</div>
 
$("#d1").data("options").name;	// "John";

creare html

$( '<p>', {
        html: 'Hello!',
        'class': 'greet'
});
$( 'li' ).html(function( index, oldHtml ) {
        return oldHtml + '!!!'
});
$(document).ready(function() {
    $('#$id').hover(function(e){
    var title = trim($(this).attr('title'));
    $(this).data('tipText', title).removeAttr('title');
 
    var position = $(this).offset();
 
    $('<p class="help_tooltip"></p>')
        .html(nl2br(title))
        .appendTo('body')
        .css({ top: 15+position.top, left: position.left })
        .fadeIn('fast');
 
    }, function() {
    $(this).attr('title', $(this).data('tipText'));
    $('.help_tooltip').remove();
    });
});

LocalStorage

$.jStorage jQuery plugin permette la compatibilità con vecchi browser( IE before version 8), l'api può essere utile per realizzare il concetto di sessione sul client.

var value = $.jStorage.get("key");
if(!value){
    // if not - load the data from the server
    value = load_data_from_server();
    // and save it
    $.jStorage.set("key",value);
}

eventi

$(window).load(function(){
        // Put your jQuery functions that should only initialize after the page has loaded.
});

useful as well a jQuery function that support chaining

$.fn.makeNotInStock = function() {
    return $(this).removeClass('in_stock').addClass('3-5_days');
}
 
$('#shopping_cart_items input.in_stock').makeNotInStock().log();

delegate: Event delegation allows you to avoid adding event listeners to specific nodes; instead, the event listener is added to one parent. imagine a list of links. serve a risparmiare memoria o rendere l'evento indipendente dal dom(si può eliminare il contenuto dei nodi e inserire nuov contenuto senza aggiornare i listeners)

$("#link-list").delegate("a", "click", function(){
        // "$(this)" is the node that was clicked
        console.log("you clicked a link!",$(this));
});

Custom Events

$(document).on('testEvent', function(e, eventInfo) {
        subscribers = $('.subscribers-testEvent');
        subscribers.trigger('testEventHandler', [eventInfo]);
});
 
$('#myButton').on('click', function() {
        $(document).trigger('testEvent', [1011]);
});
 
$('#notifier1').on('testEventHandler', function(e, eventInfo) {
        alert('(notifier1)The value of eventInfo is: ' + eventInfo);
});
 
$('#notifier2').on('testEventHandler', function(e, eventInfo) {
        alert('(notifier2)The value of eventInfo is: ' + eventInfo);
});

selectors

// almeno un elemento è trovato
if ( $("#mydiv").length > 1 ){}
 
// deprecated alias for length property
$('selector').size();
 
// Attenzione! : This is always true! $() returns empty object
if($('selector')){}

The result of running a selector is a jQuery object. However, the library makes it appear as if you are working with an array by defining index elements and a length.

// Selecting all the navigation buttons:
var buttons = $('#navigation a.button');
 
// We can loop though the collection:
for(var i=0;i<buttons.length;i++){
    console.log(buttons[i]);// A DOM element, not a jQuery object
}
$('#container li:first-child').selector(); // #container li:first-child
 
$('li')
    .find( 'span' )
    .attr( 'title', 'Hover over me' )
.click(function() {
    $( this ).addClass( 'clicked' );
});
 
$(".parent").find(".bar").filter("p");

Find all checked checkboxes:

$('input[type=checkbox]:checked');
 
// if a single checkbox is checked or not:
var is_checked = $(el).attr('checked');

element exists:

var is_found = $('#myElement').length > 0;

animazioni

<style>
div.button {
    background:#cfd;
    margin:3px;
    width:50px;
    text-align: center;
    float:left;
    cursor:pointer;
    border:2px outset black;
    font-weight:bolder;
}
#sliding { display:none; }
</style>
 
$(document).ready(function(){
    // Use jQuery to change look of div once clicked and the event to
    //start off the slide effect
    $("div.button").click(function () {
        //div.button will now look like a pushed down button
        $(this).css({ borderStyle:"inset", cursor:"wait" });
        //The hidden #sliding will now slide down and use callback to start the
        //slideup once it completes
        $('#sliding').slideDown('slow', function(){
            $('#sliding').slideUp('slow', function(){
                //once the slide up is over the callback change css for button back
                $('div.button').css({ borderStyle:"outset", cursor:"auto" });
            });
        });
    });
});
// delay() method per impostare una pausa
$('#elem').animate({width:200}).delay(2000).animate({marginTop:100});

assicurarsi che un nodo sia completamente caricato

$('#myImage').attr('src', 'image.jpg').load(function() {
        alert('Image Loaded');
        //perform action that is dependant of image being fully loaded
});

DOM manipolare il contenuto di un elemento

$('#targetdiv').replaceWith('<div>going to be inserted!</div>');

custom selectors

$.expr[':'].withRel = function(element){
    var $this = $(element);
    //simply returning elements where rel is not empty
    return ($this.attr('rel') != '');
};
 
$(document).ready(function(){
        //Using the custom selector is simple and the collection returned support chaining
        // as illustrated here to apply some css to the returned elements
        $('a:withRel').css('background-color', 'green');
});
 
// creare un nodo nel DOM
jQuery("<img>").attr("src", arguments[i]);

Deferred

promise: When you try to use the value in a promise, the program waits for the computation to complete, you retain a more synchronous-looking program.

// std way: callbacks
query(function(result) { ... }, ...);
 
// promise way:
result_promise = query(...); // Returns immediately.
do_something_else(); // Can execute immediately.
do_something_with(result_promise); // Blocks for 10 seconds.

promise ajax:

var name = $.post('/echo/json/', {json:JSON.stringify({'name':"Matt Baker"})});
var lastUpdate = $.post('/echo/json/', {json:JSON.stringify({'lastUpdate':"Hello World"})});
 
$.when(name, lastUpdate)
.done(function (nameResponse, lastUpdateResponse) {
        var name = nameResponse[0].name;
        var lastUpdate = lastUpdateResponse[0].lastUpdate;
        $("#render-me").html(name+"'s last update was: "+lastUpdate);
})
.fail(function () {
        $("#error").html("an error occured").show();
});

AJAX

js modern std:JSON.stringify() and JSON.parse() methods. older browsers: json2.js library. jQuery also provides the jQuery.parseJSON method, which provides the same functionality as JSON.parse() across all browsers. However, jQuery does not provide a method that corresponds to JSON.stringify()

var id=$("#id").attr("value");
$.getJSON('ajax/test.json', ,{id:id}, function(data) {
  $('.result').html('<p>' + data.foo + '</p>'
    + '<p>' + data.baz[1] + '</p>');
});
 
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
 
$.post("test.php", $("#testform").serialize());
 
$.post("test.php", function(data){
   alert("Data Loaded: " + data);
});

debug

logging

jQuery.fn.log = function (msg) {
    console.log("%s: %o", msg, this);
    return this;
};
//With this extension you can simply call .log() on the object you are currently addressing
$('#some_div').find('li.source > input:checkbox')
    .log("sources to uncheck")
    .removeAttr("checked");

performance

It is important to prefix a class with a tag name (here this is "input") and then it is important to descend from an ID to limit the scope of the selection: var in_stock = $('#shopping_cart_items input.in_stock');

FORM

validation

<style type="text/css">
input.error, select.error {
    border: 1px solid #b94a48;
}
input.success, select.success {
    border: 1px solid #468847;
}
</style>
$(function(){
    $("#FormNewCustomer").submit(function(event) {
 
        // assicura che i campi richiesti siano valorizzati
        function checkRequired(dataForm) {
            var err_count = 0;
            dataForm.find(':input.required').each(function(){
                // salta i bottoni
                if( this.tagName.toLowerCase() == 'button'){
                    return;
                }
                var is_empty = $.trim($(this).val()).length==0;
                if (is_empty){
                    err_count++;
                    $(this).removeClass('success').addClass('error');
                } else {
                    $(this).removeClass('error').addClass('success');
                }
            });
            if ( err_count > 0 ) {
                return false;
            } else {
                return true;
            }
        }
        var formdata = $(this);
 
        if ( formdata.length > 0 ) {
            if (checkRequired(formdata)) {
                formdata.submit();
            } else {
                var msg = "E' necessario compilare tutti le voci per il Cliente e la Destinazione";
                UI.alert(msg);
                return false;
            }
        } else {
            alert('form #FormNewCustomer non trovata ');
        }
    });
});

Plugin

basic

(function($){
        $.fn.yourPluginName = function(){
            // Your code goes here
            return this;
        };
})(jQuery);
// minimal working plugin
jQuery.fn.alertVal = function() {
    // That's our element
    var element = $(this[0]);
    if (element.val()) {
        // That's our element's value
        alert(element.val());
    }
};
$("selector").alertVal();
// jQuery Plugin Boilerplate
// A boilerplate for kick-starting jQuery plugins development
 
// remember to change every instance of "pluginName" to the name of your plugin!
(function($) {
        // here it goes!
        $.fn.pluginName = function(method) {
            // public methods
            // to keep the $.fn namespace uncluttered, collect all of the plugin's methods in an object literal and call
            // them by passing the string name of the method to the plugin
            //
            // public methods can be called as
            // element.pluginName('methodName', arg1, arg2, ... argn)
            // where "element" is the element the plugin is attached to, "pluginName" is the name of your plugin and
            // "methodName" is the name of a function available in the "methods" object below; arg1 ... argn are arguments
            // to be passed to the method
            //
            // or, from inside the plugin:
            // methods.methodName(arg1, arg2, ... argn)
            // where "methodName" is the name of a function available in the "methods" object below
            var methods = {
                // this the constructor method that gets called when the object is created
                init : function(options) {
                    // the plugin's final properties are the merged default and user-provided properties (if any)
                    // this has the advantage of not polluting the defaults, making them re-usable
                    this.pluginName.settings = $.extend({}, this.pluginName.defaults, options);
                    // iterate through all the DOM elements we are attaching the plugin to
                    return this.each(function() {
                            var $element = $(this), // reference to the jQuery version of the current DOM element
                            element = this;     // reference to the actual DOM element
                            // code goes here
                    });
                },
                // a public method. for demonstration purposes only - remove it!
                foo_public_method: function() {
                    // code goes here
                }
            }
            // private methods
            // these methods can be called only from inside the plugin
            //
            // private methods can be called as
            // helpers.methodName(arg1, arg2, ... argn)
            // where "methodName" is the name of a function available in the "helpers" object below; arg1 ... argn are
            // arguments to be passed to the method
            var helpers = {
                // a private method. for demonstration purposes only - remove it!
                foo_private_method: function() {
                    // code goes here
                }
            }
 
            // if a method as the given argument exists
            if (methods[method]) {
                // call the respective method
                return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
                // if an object is given as method OR nothing is given as argument
            } else if (typeof method === 'object' || !method) {
                // call the initialization method
                return methods.init.apply(this, arguments);
                // otherwise
            } else {
                // trigger an error
                $.error( 'Method "' +  method + '" does not exist in pluginName plugin!');
            }
        }
 
        // plugin's default options
        $.fn.pluginName.defaults = {
            foo: 'bar'
        }
        // this will hold the merged default and user-provided options
        // you will have access to these options like:
        // this.pluginName.settings.propertyName from inside the plugin or
        // element.pluginName.settings.propertyName from outside the plugin, where "element" is the element the
        // plugin is attached to;
        $.fn.pluginName.settings = {}
})(jQuery);
 
// usage
$(document).ready(function() {
    // attach the plugin to an element
    $('#element').pluginName({'foo': 'bar'});
    // call a public method
    $('#element').pluginName('foo_public_method');
    // get the value of a property
    $('#element').pluginName.settings.foo;
})

HTML Builder

var createSelect = function (elements) {
    var select = $("<select/>", {
            html: "<option>All</option>"
    });
 
    _.each(elements, function (item) {
            var option = $("<option/>", {
                    value: item.toLowerCase(),
                    text: item.toLowerCase()
            }).appendTo(select);
    });
    return select;
};

snippets

function preload_images() {
    for (var i = 0; i < arguments.length; i++) {
        $('<img>').attr('src', arguments[i]);
    }
}
preload_images('img/1.png', 'img/2.png');

scroll to top:

$('.top').click(function (e) {
    e.preventDefault();
    $('html, body').animate({scrollTop: 0}, 800);
});
// Create an anchor tag
// <a class="top" href="#">Back to top</a>

accordion

    <dl class="accordion">
        <dt><a href="">Panel 1</a></dt>
            <dd>test test</dd>
        <dt><a href="">Panel 2</a></dt>
            <dd>test test</dd>
        <dt><a href="">Panel 3</a></dt>
            <dd>test test</dd>
    </dl>
function accordion_init(selector){
   var allPanels = $('.accordion > dd').hide();
  $('.accordion > dt > a').click(function() {
    allPanels.slideUp();
    $(this).parent().next().slideDown();
    return false;
  });
}
.accordion {
   margin: 50px;
   dt, dd {
      padding: 10px;
      border: 1px solid black;
      border-bottom: 0;
      &:last-of-type {
        border-bottom: 1px solid black;
      }
      a {
        display: block;
        color: black;
        font-weight: bold;
      }
   }
  dd {
     border-top: 0;
     font-size: 12px;
     &:last-of-type {
       border-top: 1px solid white;
       position: relative;
       top: -1px;
     }
  }
}

page overlay:

    var docHeight = $(document).height();
   $("body").append("<div id='overlay'></div>");
   $("#overlay")
      .height(docHeight)
      .css({
         'opacity' : 0.4,
         'position': 'absolute',
         'top': 0,
         'left': 0,
         'background-color': 'black',
         'width': '100%',
         'z-index': 5000
      });

input placeholder:

$("#s")
    .val("Search...")
    .css("color", "#ccc")
    .focus(function(){
        $(this).css("color", "black");
        if ($(this).val() == "Search...") {
            $(this).val("");
        }
    })
    .blur(function(){
        $(this).css("color", "#ccc");
        if ($(this).val() == "") {
            $(this).val("Search...");
        }
    });

disable submit buttons:

$('input[type="submit"]').prop('disabled', true);

Open External Links in New Tab/Window

$('a[href^="http"]').attr('target', '_blank');
$('a[href^="//"]').attr('target', '_blank');
$('a[href^="' + window.location.origin + '"]').attr('target', '_self');

same height colums:

// loop over a set of elements and set the height to the height of the tallest
var $columns = $('.column');
var height = 0;
$columns.each(function () {
  if ($(this).height() > height) {
    height = $(this).height();
  }
});
$columns.height(height);

Checking If Images Are Loaded

$('img').load(function () {
  console.log('image load successful');
});

Fix Broken Images:

$('img').on('error', function () {
  if(!$(this).hasClass('broken-image')) {
    $(this).prop('src', 'img/broken.png').addClass('broken-image');
  }
});

sticky footer:

    <div id="footer">
        Sticky Footer
    </div>
    #footer { height: 100px; }
$(window).bind("load", function() {
       var footerHeight = 0,
           footerTop = 0,
           $footer = $("#footer");
       positionFooter();
       function positionFooter() {
                footerHeight = $footer.height();
                footerTop = ($(window).scrollTop()+$(window).height()-footerHeight)+"px";
               if ( ($(document.body).height()+footerHeight) < $(window).height()) {
                   $footer.css({
                        position: "absolute"
                   }).animate({
                        top: footerTop
                   })
               } else {
                   $footer.css({
                        position: "static"
                   })
               }
       }
       $(window).scroll(positionFooter).resize(positionFooter)
});

load jquery if not available:

var url = 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js';
require_once((typeof jQuery == 'undefined'), url, function() {
    // jquery loaded ...
});
function require_once(test, url, success) {
    if ( !test ) {
        return;
    }
    var script = document.createElement('script');
     script.src = url;
    var head = document.getElementsByTagName('head')[0],
    done = false;
    // Attach handlers for all browsers
    script.onload = script.onreadystatechange = function() {
        if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
        done = true;
            // callback function provided as param
            success();
            script.onload = script.onreadystatechange = null;
            head.removeChild(script);
        };
    };
    head.appendChild(script);
}

password validation:

$('#pass').keyup(function(e) {
     var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g");
     var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
     var enoughRegex = new RegExp("(?=.{6,}).*", "g");
     if (false == enoughRegex.test($(this).val())) {
             $('#passstrength').html('More Characters');
     } else if (strongRegex.test($(this).val())) {
             $('#passstrength').className = 'ok';
             $('#passstrength').html('Strong!');
     } else if (mediumRegex.test($(this).val())) {
             $('#passstrength').className = 'alert';
             $('#passstrength').html('Medium!');
     } else {
             $('#passstrength').className = 'error';
             $('#passstrength').html('Weak!');
     }
     return true;
});
    <input type="password" name="pass" id="pass"/><span id="passstrength"></span>