tutorial jQuery

Este é apenas um tutorial simples do jquery, mais um guia de referência para métodos e recursos comuns do jQuery. Para obter a documentação completa, visite http://api.jquery.com/

Um objeto jQuery contém uma coleção de elementos DOM que foram criados a partir de uma string HTML ou selecionados de um documento. O próprio objeto jQuery se comporta de forma muito semelhante a um array, ele tem uma propriedade de comprimento e os elementos no objeto podem ser acessados ​​por seus índices numéricos [0] a [comprimento-1]

estenda o protótipo jQuery fn para criar uma função ou plugin personalizado

$.fn.customFunction = function (n) {
// custom function
}

obter um objeto jQuery de um iframe

$("iFrame").contents().find("div.xclass")

para obter uma lista de eventos anexados

$.data(document, 'events')

obter elemento por id usando jQuery

var element = $('#section')[0];

O método .promise () retorna uma Promise gerada dinamicamente que é resolvida assim que todas as ações de um determinado tipo vinculadas à coleção, enfileiradas ou não, tenham terminado.

$( "div" ).promise().done(function() {
$
( "p" ).append( " Finished! " );
});

O encadeamento é possível porque cada método setter em jQuery retorna
a seleção na qual foi chamado.

var $elem = $( 'li' ).children('li').first().next();

deletar um cookie

$.cookie("name", $(this).val(), { path: '/', expires: -1 });
$
.cookie("name", $("cookie-value"), { path: '/', expires: -1 });
$
.cookie("name", null);

efeitos em jQuery

// .animate()
.animate({ fontSize: "24px" }, 1500 )

// .delay()
$
("div.second").slideUp(300).fadeIn(400);

// .fadeIn / .fadeOut()
$
("span").fadeIn(300);

// .hide()
$
("p").hide("slow");

// .show()
$
("div").show("fast");

// .stop()
$
(".block").animate({left: '+=100px'}, 2000);
$
(".block").stop();

// .toggle()
$
("p").toggle();

recuperar dados json usando ajax

// jQuery.ajax()
$
.ajax({
url
: 'ajax/test.html',
success
: function(data) {
$
('.result').html(data);
alert
('Load was performed.');
}
});

// .ajaxSuccess() / .ajaxError() / .ajaxComplete()
$
("#msg").ajaxSuccess(function(evt, request, settings){
$
(this).append("Successful Request!");
});

seletores dom

// *
// selects all elements.
var elementCount = $("*").length;

// .
// selects all elements with the given class.
$
(".myclass.otherclass")

// #
// selects a single element with the given id attribute.
$
("#myDiv")

// :animated
// select all elements that are in the progress of an animation at the time the selector is run.
$
("div:animated")

// :button
// Selects all button elements and elements of type button
$
(":button")

// :checkbox
// selects all elements of type checkbox.
$
("form input:checkbox")

// :checked
// matches all elements that are checked.
$
("input:checked")

// :contains()
// select all elements that contain the specified text.
$
("div:contains('Steven')")

// :disabled
// selects all elements that are disabled.
$
("input:disabled")

// :empty
// select all elements that have no children (including text nodes).
$
("td:empty")

// :enabled
// selects all elements that are enabled.
$
("input:enabled")

// :eq()
// select the element at index n within the matched set.
$
("td:eq(2)")

// :even :odd
// selects even / odd elements, zero-indexed.
$
("tr:even")

// :file
// selects all elements of type file.
$
("input:file")

// :first-child
// selects all elements that are the first child of their parent.
$
("div span:first-child")

// :first / :last
// selects the first / last matched element.
$
("tr:first")

// :focus
// selects element if it is currently focused.
elem
.toggleClass( "focused", elem.is(":focus") );

// :has()
// selects elements which contain at least one element that matches the specified selector.
$
("div:has(p)")

// :hidden :visible
// selects all elements that are hidden / visible.
$
("div:hidden")

// :image
// selects all elements of type image.
$
("input:image")

// :input
// selects all input, textarea, select and button elements.
$
(":input");

// :text
// selects all elements of type text.
$
("form input:text")

// :not()
// selects all elements that do not match the given selector.
$
("input:not(:checked)")

// :password
// selects all elements of type password.
$
("input:password")

// :parent
// select all elements that are the parent of another element, including text nodes.
$
("td:parent")

// :radio
// selects all elements of type radio.
$
("form input:radio")

// :reset
// selects all elements of type reset.
$
("input:reset")

// :selected
// selects all elements that are selected.
$
("select option:selected")

// :submit
// selects all elements of type submit.
$
(":submit")

alterar estilos em jQuery

// .addClass
$
("p").addClass("selected");

// .css()
var color = $(this).css("background-color");
$
(this).css("color","red");

// .hasClass
$
('#mydiv').hasClass('foo')

// .removeClass
$
("p").removeClass("blue");

// .toggleClass
$
("p").click( function () {
$
(this).toggleClass("highlight");
});

atravessando o dom em jQuery

// .add()
$
("p").add("Again")
$
("p").add("span").css("background", "yellow");

// .children()
$
("div").children()

// .closest()
var x = $("div").closest("li");

// .contents()
$
("p").contents()

// .each()
$
("li").each(function(){
$
(this).toggleClass("example");
});

// .end()
$
("p").showTags(0)
.find("span")
.css("background", "yellow")
.end()
.css("font-style", "italic");

// .eq()
$
("body").find("div").eq(2).addClass("blue");

// .find()
var $allListElements = $('li');
$
('li.item-ii').find($allListElements);

// .first()
$
('li').first().css('background-color', 'red');

// .has()
$
('li').has('ul').css('background-color', 'red');

// .is()
if ($(this).is(":first-child")) {
// execute code
}

// .last()
$
('li').last().css('background-color', 'red')

// .map()
$
(':checkbox').map(function() {
return this.id;
}).get();

// .next() / .prev()
$
('li.third-item').next().css('background-color', 'red');

// .nextAll()
// begin at the third item, we can find the elements which come after it
$
('li.third-item').nextAll().css('background-color', 'red');

// .nextUntil()
$
("#term2").nextUntil("term6")
.css("background-color", "red");

// .parent()
$
('li.item-a').parent().css('background-color', 'red');

// .parents()
// begin at item a, we can find its ancestors:
$
('li.item-a').parents().css('background-color', 'red');

// .siblings()
$
('li.third-item').siblings().css('background-color', 'red');

// .slice()
$
('li').slice(2).css('background-color', 'red');

manipulação dom em jQuery

// .after() /  .before()
$
("p").after("Hello");

// .append() / .prepend()
$
("p").append("Hello");

// .appendTo() / .prependTo()
$
("span").appendTo("#foo");

// .attr
var title = $("em").attr("title");

// .clone()
$
("b").clone().prependTo("p");

// .detach()
$
("p").detach();

// .empty()
$
("p").empty();

// .height() / .width()
$
(this).height(30)

// .html
$
("div").html("Wow...");

// .insertAfter() / .insertBefore()
$
("p").insertAfter("#foo");

// .offset()
$
("p:last").offset({ top: 10, left: 30 });

// .position()
var position = $("p").position();

// .prop
$
("input[type='checkbox']").prop({
disabled
: true
});

// .remove()
$
("p").remove();

// .text()
var str = $("p:first").text();

// .val()
var value = $(this).val();

// .wrap()
$
("p").wrap("
"
);

ligação a eventos em jQuery

// .bind()
// attach a handler to an event for the elements.
$
('#foo').bind('click', function() {
alert
('User clicked on "foo."');
});

// .unbind()
// remove a previously-attached event handler from the elements.
$
('#foo').unbind();

// .change()
// bind an event handler to the "change" javaScript event, or trigger that event on an element.
$
('.target').change(function() {
alert
('Handler for .change() called.');
});

// .click() / .dblclick
// bind an event handler to the "click" javaScript event, or trigger that event on an element.
$
("#target").click(function() {
alert
("Handler for .click() called.");
});

// .delegate()
// attach a handler to one or more events for all elements that match the selector, now or in the future
$
("table").delegate("td", "click", function() {
$
(this).toggleClass("chosen");
});

// .die()
// remove all event handlers previously attached using .live() from the elements.
$
("p").die( "click")

// .error()
// bind an event handler to the "error" JavaScript event.
$
("img")
.error(function(){
$
(this).hide();
})

// .focus()
// bind an event handler to the "focus" javaScript event, or trigger that event on an element.
$
('#target').focus(function() {
alert
('Handler for .focus() called.');
});

// .hover()
$
(function () {
$
("#mapping").hover(
function () {
$
(this).addClass("hover");
},
function () {
$
(this).removeClass("hover");
}
);
});

// .keyup() / .keypress() / .keydown()
$
('#target').keyup(function() {
alert
('Handler for .keyup() called.');
});

// .mouseover() mousedown() ...
// trigger a mouseover event.
$
('#outer').mouseover();

// .on()
// attach an event handler function for one or more events to the selected elements.
$
("#dataTable").on("click", function(event){
alert
($(this).text());
});

// .off()
// remove an event handler.
$
("p").off( "click", "**" )

// .ready()
// specify a function to execute when the DOM is fully loaded.
$
(document).ready(function() {
// Handler for .ready() called.
});

// .resize()
// bind an event handler to the "resize" javaScript event, or trigger that event on an element.
$
(window).resize(function() {
$
('#log').append('Handler for .resize() called.
'
);
});

// .scroll()
// trigger a scroll
$
('#target').scroll();

// .select()
// bind an event handler to the "select" javaScript event, or trigger that event on an element.
$
('#target').select(function() {
alert
('Handler for .select() called.');
});

// .submit()
// bind an event handler to the "submit" javaScript event, or trigger that event on an element.
$
('#target').submit(function() {
alert
('Handler for .submit() called.');
return false;
});

// .toggle()
// bind two or more handlers to the matched elements, to be executed on alternate clicks.
$
('#target').toggle(function() {
alert
('First handler for .toggle() called.');
}, function() {
alert
('Second handler for .toggle() called.');
});

// .trigger()
$
(document).ready(function(){
$
('#some-id').trigger('click');
});