'));
var n = $('div').length;
}).trigger('click');
$(document.body).click(function () {
$('div').each(function (i) {
if (this.style.color != 'blue') this.style.color = 'blue';
else this.style.color = '';
});
});
// Catch a bunch of events
$(element).on('blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu', function( event) {
console.log('event', event);
});
$('li').slice(2, 4).css('background-color', 'green');
', event);
// Toggle all checkboxes
var tog = false; // or true if they are checked on load
$('a').click(function() {
$("input[type=checkbox]").attr("checked",!tog);
tog = !tog;
});
// index of an element
$("ul > li").click(function () {
var index = $(this).prevAll().length;
});
var nextTrack = function() {
soundManager.stopAll();
if ($('li.active').next().click().length == 0) {
$('.tracks li:first').click();
}
}​;​
// see if an image is loaded
var imgsrc = 'img/image1.png';
$('').load(function(){alert('image loaded');}).error(function(){alert('error loading image');}).attr('src', imgsrc);
// Storing DATAS with elements...
var adiv = $("div").get(0);
jQuery.data(adiv, "test", { first: 16, last: "pizza!" });
$("span:first").text(jQuery.data(adiv, "test").first);
$("span:last").text(jQuery.data(adiv, "test").last);
// Or
$("div").data('storeName', 'stockValue');
alert($("div").data("storeName"));
$("div").removeData();
$("div").remove();
// When you bind a "live" event it will bind also to future elements
$("p").live("click", function(){
$(this).after("
').insertBefore(liParent);
};
```
## KEYS ##
```
var event2key = {'97':'a', '98':'b', '99':'c', '100':'d', '101':'e', '102':'f', '103':'g', '104':'h', '105':'i', '106':'j', '107':'k', '108':'l', '109':'m', '110':'n', '111':'o', '112':'p', '113':'q', '114':'r', '115':'s', '116':'t', '117':'u', '118':'v', '119':'w', '120':'x', '121':'y', '122':'z', '37':'left', '39':'right', '38':'up', '40':'down', '13':'enter'};
$(document).keypress(function(e) {
$('.l').each(function() {
if (event2key[e.which] != '' && $(this).html().charAt(0).toLowerCase() == event2key[e.which]) $(this).attr('class', 'l hightlight');
else $(this).attr('class', 'l');
});
switch(event2key[(e.which || e.keyCode)]) {
case 'left': break;
case 'right': break;
case 'up': break;
case 'down': break;
case 'enter': break;
case 'a': break;
}
});
```
## BROWSERS ##
```
$('#browser').html( 'You are using the browser: ' + $.browser.browser() );
$.browser.version.string();
$.browser.version.number();
$.browser.OS();
var firefox = $.browser.firefox();
```
## ARRAY Build in functions ##
```
jQuery.isArray( obj ) // Returns: Boolean // Added in jQuery 1.3 Determine if the parameter passed is an array.
jQuery.isFunction( obj ) // Returns: Boolean // Determine if the parameter passed is a Javascript function object.
jQuery.trim( str )
jQuery.param({width:160, height:105}); // width=160&height=105
jQuery.each( object, callback ) // Returns: Object // A generic iterator function
jQuery.extend( deep, target, object1, objectN ) // Returns: Object // Extend one object with one or more others, returning the modified object.
jQuery.grep( array, callback, invert ) // Returns: Array // Filter items out of an array, by using a filter function.
jQuery.makeArray( obj ) // Returns: Array // Turns anything into a true array.
jQuery.map( array, callback ) // Returns: Array // Translate all items in an array to another array of items.
jQuery.inArray( value, array ) // Returns: Number // Determine the index of the first parameter in the Array (-1 if not found).
jQuery.merge( first, second ) // Returns: Array // Merge two arrays together.
jQuery.unique( array ) // Returns: Array // Remove all duplicate elements from an array of elements. Note that this only works on arrays of DOM elements
// NATIVES... --------------------------------------------------------------- //
var x = [];
x.push(1);
var x = [0, 3, 1, 2];
x.reverse() // [2, 1, 3, 0]
x.join(' - ') // '2 - 1 - 3 - 0'
x.pop() // [2, 1, 3]
x.unshift(-1) // [-1, 2, 1, 3]
x.shift() // [2, 1, 3]
x.sort() // [1, 2, 3]
x.splice(1, 2) // [2, 3]
// --------------------------------------------------------------- //
x = Math.ceil(6.01); //donne x = 7
x = Math.floor(6.01); //donne x = 6
x = Math.round(6.01); //donne x = 6
x = Math.max(6,7.25); //donne x = 7.25
x = Math.min(6,7.25); //donne x = 6
x = Math.pow(3,3); //donne x = 27
x = Math.random(); //donne x = 0.6489534931546957
```
## Wait finish // Defered Done ##
* Live example : http://jsfiddle.net/molokoloco/2ZmjC/
* http://msdn.microsoft.com/en-us/scriptjunkie/gg723713.aspx
* http://jsfiddle.net/molokoloco/2ZmjC/
```
promise.then( doneCallback, failCallback )
// is equivalent to
promise.done( doneCallback ).fail( failCallback )
// http://tutorialzine.com/2011/03/custom-facebook-wall-jquery-graph/
var graphUSER = 'http://graph.facebook.com/'+options.id+'/?fields=name,picture&callback=?',
graphPOSTS = 'http://graph.facebook.com/'+options.id+'/posts/?callback=?&date_format=U&limit='+options.limit;
$.when($.getJSON(graphUSER),$.getJSON(graphPOSTS)).done(function(user,posts){
// user[0] contains information about the user (name and picture);
// posts[0].data is an array with wall posts;
var fb = {
user : user[0],
posts : []
};
$.each(posts[0].data,function(){
if(this.type != 'link' && this.type!='status'){
return true;
}
this.from.picture = fb.user.picture;
fb.posts.push(this);
});
// Rendering the templates:
$('#headingTpl').tmpl(fb.user).appendTo('body');
});
```
// From : http://stackoverflow.com/questions/6538470/jquery-deferred-waiting-for-multiple-ajax-requests-to-finish
```
function updateAllNotes () {
var getarray = [], i, len;
for (i = 0, len = data.length; i < len; i += 1) {
getarray.push(getNote(data[i].key));
};
$.when.apply($, getarray).done(function () {
// do things that need to wait until ALL gets are done
});
};
```
```
$.ajaxSetup({
dataType: "jsonp"
});
function getTweets() {
$.ajax("http://api.twitter.com/statuses/user_timeline/danwellman.json", {
success: function(data) {
var arr = [];
for (var x = 0; x < 5; x++) {
var dataItem = {};
dataItem["tweetlink"] = data[x].id_str;
dataItem["timestamp"] = convertDate(data, x);
dataItem["text"] = breakTweet(data, x);
arr.push(dataItem);
}
tweetData = arr;
}
});
}
function getFriends() {
/* ... */
}
function getFollows() {
/* ... */
}
//execute once all requests complete
$.when(getTweets(), getFriends(), getFollows()).then(function(){
//apply templates
});
```
```
var fetchTweets = function() {
var dfd = new $.Deferred();
$.ajax({
type: 'GET',
dataType: 'jsonp',
url: 'http://search.twitter.com/search.json?q=html5',
success: function(tweets) {
var twitter = $.map(tweets.results, function(obj, index) {
return {
username: obj.from_user,
tweet: obj.text,
imgSource: obj.profile_image_url,
geo: obj.geo
};
});
dfd.resolve(twitter);
}
});
return dfd.promise();
};
$.when(fetchTweets()).done(function(twitter) {
console.log(twitter);
});
```
```
var Menu = (function(){
var init = function() {
loadPage();
},
loadPage = function() {
$ac_loading.show();
$.when(loadImages()).done(function(){
/* ... */
});
},
loadImages = function() {
return $.Deferred(
function(dfd) {
var total_images = $ItemImages.length,
loaded = 0;
for(var i = 0; i < total_images; ++i){
$('').load(function() {
++loaded;
if (loaded === total_images) dfd.resolve();
}).attr('src' , $ItemImages[i]);
}
}
).promise();
};
return {
init : init
};
})();
Menu.init();
```
The Promise exposes only the Deferred methods needed to attach additional handlers or determine the state (then, done, fail, always,pipe, progress, and state), but not ones that change the state (resolve, reject, progress, resolveWith, rejectWith, and progressWith).
```
function getData(){
return $.get('/echo/html/');
}
function showDiv(){
var dfd = $.Deferred();
$('#foo').fadeIn( 1000, dfd.resolve );
return dfd.promise();
}
$.when( getData(), showDiv() )
.then(function( ajaxResult ){
console.log('The animation AND the AJAX request are both done!');
// ‘ajaxResult’ is the server’s response
});
```
* jQuery.Deferred() A constructor that creates a new Deferred object, can take an optional initFunction parameter that will be called right after the deferred has been constructed.
* jQuery.when() A way to execute callback functions based on one or more objects that represent asynchronous tasks.
* jQuery.ajax() Performs an asynchronous Ajax requests where the jqXHR objects returned by $.ajax() implement the Promise interface, giving them all the properties, methods, and behaviour of a Promise.
* deferred.then(resolveCallback,rejectCallback) Handlers to be called when the Deferred object is resolved or rejected.
* deferred.done() Functions or array of functions that are called when the Deferred object is resolved.
* deferred.fail() Functions or array of functions that are called when the Deferred is rejected.
* deferred.resolve(arg1, arg2, ...) Resolve a Deferred object and call any 'done' Callback with the given arguments.
* deferred.resolveWith(context,args) Resolve a Deferred object and call any 'done' Callback with the given context and arguments.
* deferred.isResolved Determine whether a Deferred object has been resolved.
* deferred.reject(arg1, arg2, ...) Reject a Deferred object and call any 'fail' Callback with the given arguments.
* deferred.rejectWith(context,args) Reject a Deferred object and call any 'fail' Callback with the given context and arguments.
* deferred.promise() Returns a promise, that is an immutable view of the deferred object: the promise can be passed around safely since the underlying deferred cannot be resolved or rejected through it.
## PROXY ##
```
setTimeout($.proxy( function () {
// "this" now refers to our element as we wanted
$( this ).addClass( "active" );
}, this), 500);
```
## ANIMATE ##
* http://www.robertpenner.com/easing/easing_demo.html
* http://www.learningjquery.com/2009/02/quick-tip-add-easing-to-your-animations
* http://coding.smashingmagazine.com/2011/10/04/quick-look-math-animations-javascript/
```
// Short !
$('.block').animate({width:'70%', fontSize:'3em', borderWidth:'10px'}, 1500);
$('div#mydiv').slideUp(300).delay(800).fadeIn(400);
// Full function...
$('#myDiv').animate({ // what we are animating
opacity:0,
width:'toggle',
height:150
}, {
duration: 'fast', // how fast we are animating or in seconds
easing: 'swing', // the type of easing
specialEasing: {
width: 'linear',
height: 'easeOutBounce'
},
step: function(now, fx) {
var data = fx.elem.id + ' ' + fx.prop + ': ' + now;
$('body').append('
' + data + '
');
}
complete: function() { // the callback
alert('done');
$(this).addClass('done');
}
}
);
// Optionnal parameter... milliseconds setInterval
jQuery.fx.interval = 100;
// hook into jQuery's animation mechanism by adding a property to the jQuery.fx.step object:
$.fx.step["someCSSProp"] = function(fx){
$.cssHooks["someCSSProp"].set( fx.elem, fx.now + fx.unit );
};
// Be carefull when use animate...
$('.page').stop().animate({width: '20%'}, 200);
// jQuery automaticcaly put overflow:hidden no element..
// to override this... put in CSS style :
.page { overflow: visible !important; }
```
```
// HELPERS native SETTIMEOUT (setTimeout)
setTimeout("alert('bouh');"); // buys you some time until the DOM elements are loaded
setTimeout(maFonction, 60 * 1000); // in 60 seconds
var arg = 'bouh !',
myTimeout = setTimeout(function(_arg) {
alert(_arg);
}, 10*1000, arg); // Pass callback argument at the end !
if (Math.rand() > 0.5) clearTimeout(myTimeout); // Don't bouh ?
```
## Chaining ASYNC method ##
* http://kenneth.kufluk.com/blog/2010/08/chaining-asynchronous-methods-in-jquery-using-the-queue/
```
$.fn.makeYellowForFiveSeconds = function() {
// I'm only using actions which act on jQuery objects, so I don't need to use 'each' as above.
this.css( { 'background-color' : 'yellow', color : 'yellow' } );
// reset the colour in five seconds time
var that = this;
this.queue(function() {
setTimeout(function() {
that.css( { 'background-color' : 'none', color : 'inherit' } );
that.dequeue();
}, 5000);
});
// action the next method in the chain
return this;
};
```
## Emulating 3D with CSS... ##
```
/*
#
# .photoflat {
# -moz-transform: scale(1) rotate(0deg) translate(0px, 0px) skew(-21deg, 10deg);
# transform-origin: 0% 0%;
# -webkit-transform: scale(1) rotate(0deg) translate(0px, 0px) skew(-21deg, 10deg);
# -moz-box-shadow:0px 1px 3px #333333 ;
# -webkit-box-shadow:0px 1px 3px #333333;
# box-shadow:0px 1px 3px #333333;
# margin-left:-43px;
# border:1px solid white;
# position:relative;
# }
*/
$(this).css('-moz-transform', 'scale(' + dist + ') skew(' + skew2 +'deg, 0deg)');
$(this).css('-webkit-transform', 'scale(' + dist + ') skew(' + skew2 +'deg, 0deg)');
var d = 0;
setInterval(
function () { div.style['MozTransform'] = 'rotate(' + (d++ % 360) + 'deg)'; },
100
);
```
```
$(this).hide('puff', {}, 1000);
/*
Effects that can be used with Show/Hide/Toggle:
Blind - Blinds the element away or shows it by blinding it in.
Clip - Clips the element on or off, vertically or horizontally.
Drop - Drops the element away or shows it by dropping it in.
Explode - Explodes the element into multiple pieces.
Fold - Folds the element like a piece of paper.
Puff - Scale and fade out animations create the puff effect.
Slide - Slides the element out of the viewport.
Scale - Shrink or grow an element by a percentage factor.
Effects that can be only used stand-alone:
Bounce - Bounces the element vertically or horizontally n-times.
Highlight - Highlights the background with a defined color.
Pulsate - Pulsates the opacity of the element multiple times.
Shake - Shakes the element vertically or horizontally n-times.
Size - Resize an element to a specified width and height.
Transfer - Transfers the outline of an element to another.
*/
```
Request animation
```
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(/* function */ callback, /* DOMElement */ element){
window.setTimeout(callback, 1000 / 60);
};
})();
function render() {
// do something
window.requestAnimFrame(render);
}
render();
```
## Templating ##
http://net.tutsplus.com/tutorials/javascript-ajax/fun-with-jquery-templating-and-ajax/
```
```
```
```
```
$.ajax({
type : 'GET',
dataType : 'jsonp',
url : 'http://search.twitter.com/search.json?q=nettuts',
success : function(tweets) {
var twitter = $.map(tweets.results, function(obj, index) {
return {
username : obj.from_user,
tweet : obj.text,
imgSource : obj.profile_image_url,
geo : obj.geo
};
});
}
});
```
```
```
## Elements methodes ##
```
$('a:first').offset();
/*
offset()// Returns: Object{top,left} // Get the current offset of the first matched element, in pixels, relative to the document.
position()// Returns: Object{top,left} // Gets the top and left position of an element relative to its offset parent.
scrollTop()// Returns: Integer // Gets the scroll top offset of the first matched element.
scrollTop(val)// Returns: jQuery // When a value is passed in, the scroll top offset is set to that value on all matched elements.
scrollLeft()// Returns: Integer // Gets the scroll left offset of the first matched element.
scrollLeft(val)// Returns: jQuery // When a value is passed in, the scroll left offset is set to that value on all matched elements.
height()// Returns: Integer // Get the current computed, pixel, height of the first matched element.
height(val) // Returns: jQuery // Set the CSS height of every matched element.
width()// Returns: Integer // Get the current computed, pixel, width of the first matched element.
width(val)// Returns: jQuery // Set the CSS width of every matched element.
innerHeight()// Returns: Integer // Gets the inner height (excludes the border and includes the padding) for the first matched element.
innerWidth()// Returns: Integer // Gets the inner width (excludes the border and includes the padding) for the first matched element.
outerHeight(margin)// Returns: Integer // Gets the outer height (includes the border and padding by default) for the first matched element.
outerWidth(margin)// Returns: Integer // Get the outer width (includes the border and padding by default) for the first matched element.
*/
// To get the width and height of the whole page (document)
var pageWidth = $(document).width();
var pageHeight = $(document).height();
// To get the width and height of the viewport (window)
var viewportWidth = $(window).width();
var viewportHeight = $(window).height();
```
## PARSING XML (IE compatible) ##
```
var xmlParse = function (xml) {
if ($.browser.msie) { // IE !!!
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.loadXML(xml);
xml = xmlDoc;
}
$(xml).find("article").each(function(i) {
$('#news').append($(this).find("titre").text());
});
};
$(document).ready(function(){
$.ajax({
type: 'GET',
url: './xml/parisien.xml',
cache: true,
processData: true,
dataType: ($.browser.msie) ? 'text' : 'xml',
//error: function(xml) { db('error()'); },
success: function(xml) { xmlParse(xml); }
});
});
```
## AJAX AND JSON ##
```
$.getJSON(
"http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?",
function(data){
$.each(data.items, function(i,item){
$("").attr("src", item.media.m).appendTo("#images");
if ( i == 3 ) return false;
});
}
);
// ou encore
$.get(url)
.fail(function(e) {
callback(e, null);
})
.done(function(data) {
callback(null, data);
});
// Pass Parameters Through the GET Method
$("#load_get").click(function(){
$("#result")
.html("")
.load(loadUrl+' div#content', "language=php&version=5"); // + extract content
});
// Long Polling (recursive AJAX) - An Efficient Server-Push Technique
(function poll(){
$.ajax({url: "server", success: function(data){
// Update your dashboard gauge
salesGauge.setValue(data.value);
}, dataType: "json", complete: poll, timeout: 30000});
})();
// --------------------------------------------------------------- //
// DISTANT JSON // http://blog.jaysalvat.com/articles/comprendre-jsonp-et-acces-de-donnees-a-distance-en-javascript.php
// --------------------------------------------------------------- //
var req = $.ajax({
type: 'POST',
url: 'some.php',
cache: false,
data: 'name=John&location=Boston',
success: function(msg){
alert( 'Data Saved: ' + msg );
}
});
//Cancel the Ajax Request ?
req.abort()
$.post('test.php', { name: 'John', time: '2pm' }, function(data){
alert('Data Loaded: ' + data);
});
$.post('test.php', { func: 'getNameAndTime' }, function(data){
alert(data.name); // John
console.log(data.time); // 2pm
}, 'json');
var html = $.ajax({
url: 'some.php',
async: false
}).responseText;
$.ajax({
url: 'page.php',
processData: false,
data: [/*create xml document*/],
success: handleResponse
});
var obj = jQuery.parseJSON('{"name":"Larry King", "age": "5000"}');
alert(obj.name);
// MAPPING COMPLEX JSON
function youtube(callback) {
var url = "http://gdata.youtube.com/feeds/api/videos/-/Comedy?v=2&alt=json-in-script&start-index=" + startIndex + "&callback=?";
jQuery.getJSON(url, function (data) {
var images = jQuery.map(data.feed.entry, function (item) {
return {
title: item.title.$t,
thumb: item.media$group.media$thumbnail[0].url,
ytvideoid: item.media$group.yt$videoid.$t,
videoloader: youtubevideo,
link: item.link[0].href
};
});
startIndex += images.length;
callback(images);
});
}
```
## Somes Functions ... ##
```
// Get URL parameters values
$.extend({
getUrlVars: function() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { vars[key] = value; });
return vars;
}
});
var name = $.getUrlVars()['name'];
// --------------------------------------------------------------- //
// scale elements to fit box
(function($){
$.fn.extend({
fluwi: function(opt){
var variate = ((opt.variate!= undefined)?opt.variate:0);
var contWidth = this.outerWidth();
var boxWidth = opt.minWidth;
var counted = Math.floor(contWidth/boxWidth);
var extra = contWidth-boxWidth*counted;
var eachOne = extra/counted;
$(opt.boxQuery).css("width", (parseInt(boxWidth)+(eachOne))-variate);
}
});
})(jQuery);
// The plugin call code
$('#mydiv').fluwi({
minWidth: 200, //pixels
variate: 2, //pixels
boxQuery: 'li' //class name or div name, or selector for elements that are resizing
});
// MENU
/*
margin
colWidth: null, // As in the CSS, choose between COUNT or WIDTH for cols
colCount: 2, // colWidth (px) OR colCount (num)
chapters: 'h1,h2,h3,h4,h5,h6', // Between the H1-Hx ()
take: 'p', // Take all the p (ul,quote,..) NEXT() to each chapters
css: 'multiplecolumns', // And wrap them with class
minLine: 2, // If less than 3 lines, don't wrap with columns
maxHeight: null // Max col height will be..
};
/* COLONIZR NO CONFLICT
* ===================== */
$.fn.colonizr.noConflict = function () {
$.fn.colonizr = old;
return this;
};
/* COLONIZR DATA-API
* ================== */
$(window).on('load', function () {
$('[data-colonizr="true"]').each(function () {
var $spy = $(this);
$spy.colonizr($spy.data());
})
});
}(window.jQuery);
/////////////////////////////////////////////////////////////////
// Usage example... /////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
var $container = $('div#container');
$('a#colonize').click(function() { // Call on click
$container.colonizr({ // Use plugin...
marge: 10,
colWidth: 180, // Report CSS "column-width"
take: 'p,ul', // Adding UL to the stream...
css: 'multiplecolumns' // If you want to change the CSS..
});
});
var windowTmr = null; // Timeout...
var resizeRefreshEvent = function() { // Trottle resize...
windowTmr = null;
if ($container.data('colonizr')) // Colonizr was applyed by user click ?
$container.colonizr('refresh'); // Refresh cols height...
};
$(window).on('resize', function(event) { // Resize Event
if (windowTmr) clearTimeout(windowTmr);
windowTmr = setTimeout(resizeRefreshEvent, 1600); // Trottle resize
});
```