Create DOM elements on-the-fly from the provided String of raw HTML.
Cria elementos DOM por cima da String fornecida do HTML.
Creates a div element (and all of its contents) dynamically, and appends it to the element with the ID of body. Internally, an element is created and it's innerHTML property set to the given markup. It is therefore both quite flexible and limited.
Cría um elemento div (e todo seu conteúdo) dinâmicamente, e adiciona-os ao elemento com o ID do Body. Internamente, um elemento é criado e a propriedade do innerHTML põe ao alvo fornecido. É conseqüentemente ambos completamente flexíveis e limitados.
$("<div><p>Hello</p></div>").appendTo("#body")
Wrap jQuery functionality around a single or multiple DOM Element(s).
This function also accepts XML Documents and Window objects as valid arguments (even though they are not DOM Elements).
Funcionalidade jQuery de envolver um único ou múltiplos elementos de DOM.
Esta função aceita Documentos XML e um leque de objetos válidos (mesmo que não sejam elementos DOM).
Sets the background color of the page to black.
Seta a cor do fundo da página para preto.
$(document.body).background( "black" );
Hides all the input elements within a form
Esconde todos os elementos que estejam dentro de um formulário
$( myForm.elements ).hide()
A shorthand for $(document).ready(), allowing you to bind a function to be executed when the DOM document has finished loading. This function behaves just like $(document).ready(), in that it should be used to wrap all of the other $() operations on your page. While this function is, technically, chainable - there really isn't much use for chaining against it. You can have as many $(document).ready events on your page as you like.
Uma abreviação para $ (document).ready (), permitindo que você acione uma função a ser executada quando o documento DOM terminar o carregamento. Esta função comporta-se justamente como $(document).ready (), que deve ser usado envolvendo todas as outras operações de $() em sua página.
See ready(Function) for details about the ready event.
Ver Funcionando(Function) para detalhes sobre o evento funcionando.
Executes the function when the DOM is ready to be used.
Executa a função quando o DOM estiver carregado e pronto para ser usado.
$(function(){
// Document is ready
});
Uses both the shortcut for $(document).ready() and the argument to write failsafe jQuery code using the $ alias, without relying on the global alias.
Usa o atalho para $ (document).ready() e o argumento escreve o código failsafe do jQuery usando o $ alias, sem confiar no global aliás.
jQuery(function($) {
// Your code using failsafe $ alias here...
});
This function accepts a string containing a CSS or basic XPath selector which is then used to match a set of elements.
The core functionality of jQuery centers around this function. Everything in jQuery is based upon this, or uses this in some way. The most basic use of this function is to pass in an expression (usually consisting of CSS or XPath), which then finds all matching elements.
By default, $() looks for DOM elements within the context of the current HTML document.
Esta função aceita uma corda que contem um CSS ou um seletor básico de XPath que seja usado então combinar um jogo dos elementos.
A funcionalidade do núcleo do jQuery centra-se em torno desta função. Tudo no jQuery é baseado neste, ou usa este em alguma maneira. O uso o mais básico desta função é passar em uma expressão (CSS geralmente consistindo ou XPath), que encontre então todos os elementos combinando.
Pelo defeito, $ () procura elementos de DOM dentro do contexto do original atual do HTML.
Finds all p elements that are children of a div element.
Encontra todos os elementos de p que são crianças de um elemento do div.
$("div > p")
<p>one</p> <div><p>two</p></div> <p>three</p>
[ <p>two</p> ]
Searches for all inputs of type radio within the first form in the document
Buscas para todas as entradas do tipo rádio dentro do primeiro formulário no original
$("input:radio", document.forms[0])
This finds all div elements within the specified XML document.
Isto encontra todos os elementos do div dentro do original especificado de XML.
$("div", xml.responseXML)
Extends the jQuery object itself. Can be used to add functions into the jQuery namespace and to add plugin methods (plugins).
Estende o objeto próprio do jQuery. Pode ser usado adicionar funções no namespace do jQuery e adicionar métodos plugin (encaixes).
Object
Adds two plugin methods.
Adiciona dois métodos plugin.
jQuery.fn.extend({
check: function() {
return this.each(function() { this.checked = true; });
},
uncheck: function() {
return this.each(function() { this.checked = false; });
}
});
$("input[@type=checkbox]").check();
$("input[@type=radio]").uncheck();
Adds two functions into the jQuery namespace
Adiciona duas funções no namespace do jQuery
jQuery.extend({
min: function(a, b) { return a < b ? a : b; },
max: function(a, b) { return a > b ? a : b; }
});
Run this function to give control of the $ variable back to whichever library first implemented it. This helps to make sure that jQuery doesn't conflict with the $ object of other libraries.
By using this function, you will only be able to access jQuery using the 'jQuery' variable. For example, where you used to do $("div p"), you now must do jQuery("div p").
Funcionar esta função para dar para trás o controle da variável de $ a qualquer biblioteca a executou primeiramente. Isto ajuda certificar-se de que o jQuery não opõe ao objeto de $ de outras bibliotecas.
Usando esta função, você somente alcança o jQuery usando a variável do “jQuery”. Por exemplo, onde você se usou fazer $ (“div p”), você agora deve fazer o jQuery (“div p”).
Maps the original object that was referenced by $ back to $
Traça o objeto original que referenced por $ para trás a $
jQuery.noConflict();
// Do something with jQuery
jQuery("div p").hide();
// Do something with another library's $()
$("content").style.display = 'none';
Reverts the $ alias and then creates and executes a function to provide the $ as a jQuery alias inside the functions scope. Inside the function the original $ object is not available. This works well for most plugins that don't rely on any other library.
Reverts o $ aliás e então cría e executa uma função para fornecer o $ como um jQuery aliás dentro do espaço das funções. Dentro da função o objeto original de $ não está disponível. Isto trabalha bem para a maioria de encaixes que não confiam em nenhuma outra biblioteca.
jQuery.noConflict();
(function($) {
$(function() {
// more code using $ as alias to jQuery
});
})(jQuery);
// other code using $ as an alias to the other library
Execute a function within the context of every matched element. This means that every time the passed-in function is executed (which is once for every element matched) the 'this' keyword points to the specific element.
Additionally, the function, when executed, is passed a single argument representing the position of the element in the matched set.
Executar uma função dentro do contexto de cada elemento combinado. Isto significa que cada vez que pass-na função está executado (que é uma vez para cada elemento combinado) “este” keyword aponta ao elemento específico.
Adicionalmente, a função, quando executada, é passada a um único argumento que representa a posição do elemento no jogo combinado.
Iterates over two images and sets their src property
Itera sobre duas imagens e ajusta sua propriedade do src
$("img").each(function(i){
this.src = "test" + i + ".jpg";
});
<img/><img/>
<img src="test0.jpg"/><img src="test1.jpg"/>
Reduce the set of matched elements to a single element. The position of the element in the set of matched elements starts at 0 and goes to length - 1.
Reduzir o jogo de elementos combinados a um único elemento. A posição do elemento no jogo de elementos combinados começa por 0 e vai ao comprimento - 1.
$("p").eq(1)
<p>This is just a test.</p><p>So is this</p>
[ <p>So is this</p> ]
Access all matched elements. This serves as a backwards-compatible way of accessing all matched elements (other than the jQuery object itself, which is, in fact, an array of elements).
Alcançar todos os elementos combinados. Isto serve como uma maneira para trás-compatível de alcançar todos os elementos combinados (à excepção do objeto próprio do jQuery, que é, no fato, em uma disposição dos elementos).
Array<Element>
Selects all images in the document and returns the DOM Elements as an Array
Seleciona todas as imagens no original e retorna os elementos de DOM como uma disposição
$("img").get();
<img src="test1.jpg"/> <img src="test2.jpg"/>
[ <img src="test1.jpg"/> <img src="test2.jpg"/> ]
Access a single matched element. num is used to access the Nth element matched.
Alcançar um único elemento combinado. numérico é usado alcançar o Nth elemento combinado.
Element
Selects all images in the document and returns the first one
Seleciona todas as imagens no original e retorna primeiro
$("img").get(0);
<img src="test1.jpg"/> <img src="test2.jpg"/>
[ <img src="test1.jpg"/> ]
Reduce the set of matched elements to all elements after a given position. The position of the element in the set of matched elements starts at 0 and goes to length - 1.
Reduzir o jogo de elementos combinados a todos os elementos após uma posição dada. A posição do elemento no jogo de elementos combinados começa por 0 e vai ao comprimento - 1.
$("p").gt(0)
<p>This is just a test.</p><p>So is this</p>
[ <p>So is this</p> ]
Searches every matched element for the object and returns the index of the element, if found, starting with zero. Returns -1 if the object wasn't found.
Procurara cada elemento combinado pelo objeto e retorna o índice do elemento, se encontrado, começando com zero. Retorna -1 se o objeto não for encontrado.
Number
Returns the index for the element with ID foobar
Retorna o índice para o elemento com o ID foobar
$("*").index( $('#foobar')[0] )
<div id="foobar"><b></b><span id="foo"></span></div>
0
Returns the index for the element with ID foo within another element
Retorna o índice para o elemento com o foo do ID dentro de um outro elemento
$("*").index( $('#foo')[0] )
<div id="foobar"><b></b><span id="foo"></span></div>
2
Returns -1, as there is no element with ID bar
Os retornos -1, como lá não são nenhum elemento com barra do ID
$("*").index( $('#bar')[0] )
<div id="foobar"><b></b><span id="foo"></span></div>
-1
The number of elements currently matched.
O número dos elementos combinou atualmente.
Number
$("img").length;
<img src="test1.jpg"/> <img src="test2.jpg"/>
2
Reduce the set of matched elements to all elements before a given position. The position of the element in the set of matched elements starts at 0 and goes to length - 1.
Reduzir o jogo de elementos combinados a todos os elementos antes de uma posição dada. A posição do elemento no jogo de elementos combinados começa por 0 e vai ao comprimento - 1.
$("p").lt(1)
<p>This is just a test.</p><p>So is this</p>
[ <p>This is just a test.</p> ]
The number of elements currently matched.
O número dos elementos combinou atualmente.
Number
$("img").size();
<img src="test1.jpg"/> <img src="test2.jpg"/>
2
Adds the specified class(es) to each of the set of matched elements.
Adiciona a classe especificada a cada um dos quadro de elementos combinados.
$("p").addClass("selected")
<p>Hello</p>
[ <p class="selected">Hello</p> ]
$("p").addClass("selected highlight")
<p>Hello</p>
[ <p class="selected highlight">Hello</p> ]
Access a property on the first matched element. This method makes it easy to retrieve a property value from the first matched element.
Alcança uma propriedade no primeiro elemento combinado. Este método facilmente recupera um valor da propriedade do primeiro elemento combinado.
Object
Returns the src attribute from the first image in the document.
Retorna o atributo src da primeira imagem do documento.
$("img").attr("src");
<img src="test.jpg"/>
test.jpg
Set a key/value object as properties to all matched elements.
A chave/valor junta-se para ajustar-se como propriedades do objeto.
This serves as the best way to set a large number of properties
This serves as the best way to set a large number of properties on all matched elements.
Sets src and alt attributes to all images.
Ajusta o src e os atributos do alt a todas as imagens.
$("img").attr({ src: "test.jpg", alt: "Test Image" });
<img/>
<img src="test.jpg" alt="Test Image"/>
Set a single property to a value, on all matched elements.
Ajusta uma única propriedade a um valor, em todos os elementos combinados.
Can compute values provided as ${function}, see second example.
Pode computar os valores fornecidos como ${function}, vêem o segundo exemplo.
Note that you can't set the name property of input elements in IE. Use $(html) or .append(html) or .html(html) to create elements on the fly including the name property.
Note que você não pode ajustar a propriedade conhecida de elementos da entrada no IE. Usar $ (HTML) ou .append(HTML) ou .html (HTML) para criar elementos incluindo a propriedade conhecida.
Sets src attribute to all images.
Ajusta o atributo src a todas as imagens.
$("img").attr("src","test.jpg");
<img/>
<img src="test.jpg"/>
Sets title attribute from src attribute, a shortcut for attr(String,Function)
Ajusta o título do atributo src, um atalho do título para o attr(String,Function)
$("img").attr("title", "${this.src}");
<img src="test.jpg" />
<img src="test.jpg" title="test.jpg" />
Set a single property to a computed value, on all matched elements.
Ajustar uma única propriedade a um valor computado, em todos os elementos combinados.
Instead of a value, a function is provided, that computes the value.
Em vez de um valor, uma função é fornecida, que compute o valor.
Sets title attribute from src attribute.
Ajusta o atributo do título do atributo do src.
$("img").attr("title", function() { return this.src });
<img src="test.jpg" />
<img src="test.jpg" title="test.jpg" />
Enumerate title attribute.
Enumerar o atributo do título
$("img").attr("title", function(index) { return this.title + (i + 1); });
<img title="pic" /><img title="pic" /><img title="pic" />
<img title="pic1" /><img title="pic2" /><img title="pic3" />
Get the html contents of the first matched element. This property is not available on XML documents.
Começar os índices do HTML do primeiro elemento combinado. Esta propriedade não está disponível em documentos XML.
String
$("div").html();
<div><input/></div>
<input/>
Set the html contents of every matched element. This property is not available on XML documents.
Ajustar os índices do HTML de cada elemento combinado. Esta propriedade não está disponível em documentos XML.
$("div").html("<b>new stuff</b>");
<div><input/></div>
<div><b>new stuff</b></div>
Remove an attribute from each of the matched elements.
Remover um atributo de cada um dos elementos combinados.
$("input").removeAttr("disabled")
<input disabled="disabled"/>
<input/>
Removes all or the specified class(es) from the set of matched elements.
Remove tudo ou a classe especificada do quadro de elementos combinados.
$("p").removeClass()
<p class="selected">Hello</p>
[ <p>Hello</p> ]
$("p").removeClass("selected")
<p class="selected first">Hello</p>
[ <p class="first">Hello</p> ]
$("p").removeClass("selected highlight")
<p class="highlight selected first">Hello</p>
[ <p class="first">Hello</p> ]
Get the text contents of all matched elements. The result is a string that contains the combined text contents of all matched elements. This method works on both HTML and XML documents.
Começar os índices do texto de todos os elementos combinados. O resultado é uma string que contenha os índices combinados do texto de todos os elementos combinados. Este método trabalha com documentosHTML e XML.
String
Gets the concatenated text of all paragraphs
Começa o texto concatenado de todos os parágrafos
$("p").text();
<p><b>Test</b> Paragraph.</p><p>Paraparagraph</p>
Test Paragraph.Paraparagraph
Set the text contents of all matched elements.
Ajustar os índices do texto de todos os elementos combinados.
Similar to html(), but escapes HTML (replace "<" and ">" with their HTML entities).
Similar to html(), but escapes HTML (replace "<" and ">" with their HTML entities). Similar ao html(), mas escapa HTML (substituir "<" and ">" com suas entidades HTML).
String
Sets the text of all paragraphs.
Ajusta o texto de todos os parágrafos.
$("p").text("<b>Some</b> new text.");
<p>Test Paragraph.</p>
<p><b>Some</b> new text.</p>
Sets the text of all paragraphs.
$("p").text("<b>Some</b> new text.", true);
<p>Test Paragraph.</p>
<p>Some new text.</p>
Adds the specified class if it is not present, removes it if it is present.
Adiciona a classe especificada se não estiver atual, remove-a se estiver atual.
$("p").toggleClass("selected")
<p>Hello</p><p class="selected">Hello Again</p>
[ <p class="selected">Hello</p>, <p>Hello Again</p> ]
Get the current value of the first matched element.
Começar o valor atual do primeiro elemento combinado.
String
$("input").val();
<input type="text" value="some text"/>
"some text"
Set the value of every matched element.
Ajustar o valor de cada elemento combinado.
$("input").val("test");
<input type="text" value="some text"/>
<input type="text" value="test"/>
Insert content after each of the matched elements.
Introduzir o índice após cada um dos elementos combinados.
Inserts some HTML after all paragraphs.
Introduz algum HTML após todos os parágrafos.
$("p").after("<b>Hello</b>");
<p>I would like to say: </p>
<p>I would like to say: </p><b>Hello</b>
Inserts an Element after all paragraphs.
Introduz um elemento após todos os parágrafos.
$("p").after( $("#foo")[0] );
<b id="foo">Hello</b><p>I would like to say: </p>
<p>I would like to say: </p><b id="foo">Hello</b>
Inserts a jQuery object (similar to an Array of DOM Elements) after all paragraphs.
Introduz um objeto do jQuery (similar a uma disposição de elementos de DOM) após todos os parágrafos.
$("p").after( $("b") );
<b>Hello</b><p>I would like to say: </p>
<p>I would like to say: </p><b>Hello</b>
Append content to the inside of every matched element.
This operation is similar to doing an appendChild to all the specified elements, adding them into the document.
Adicionar o índice ao interior de cada elemento combinado. Esta operação é similar a fazer um appendChild a todos os elementos especificados, adicionando os no original.
Appends some HTML to all paragraphs.
Adiciona algum HTML a todos os parágrafos.
$("p").append("<b>Hello</b>");
<p>I would like to say: </p>
<p>I would like to say: <b>Hello</b></p>
Appends an Element to all paragraphs.
Adiciona um elemento a todos os parágrafos.
$("p").append( $("#foo")[0] );
<p>I would like to say: </p><b id="foo">Hello</b>
<p>I would like to say: <b id="foo">Hello</b></p>
Appends a jQuery object (similar to an Array of DOM Elements) to all paragraphs.
Adiciona um objeto do jQuery (similar a uma disposição de elementos de DOM) a todos os parágrafos.
$("p").append( $("b") );
<p>I would like to say: </p><b>Hello</b>
<p>I would like to say: <b>Hello</b></p>
Append all of the matched elements to another, specified, set of elements. This operation is, essentially, the reverse of doing a regular $(A).append(B), in that instead of appending B to A, you're appending A to B.
Adicionar todos os elementos combinados a outros, especificado, jogo dos elementos. Esta operação é, essencialmente, o reverso de fazer um $ regular (A) .juntar (B), nisso em vez de adicionar B a A, você está adicionando A a B.
Appends all paragraphs to the element with the ID "foo"
Adiciona todos os parágrafos ao elemento com o ID "foo"
$("p").appendTo("#foo");
<p>I would like to say: </p><div id="foo"></div>
<div id="foo"><p>I would like to say: </p></div>
Insert content before each of the matched elements.
Introduzir o índice antes de cada um dos elementos combinados.
Inserts some HTML before all paragraphs.
Introduz algum HTML antes de todos os parágrafos.
$("p").before("<b>Hello</b>");
<p>I would like to say: </p>
<b>Hello</b><p>I would like to say: </p>
Inserts an Element before all paragraphs.
Introduz um elemento antes de todos os parágrafos.
$("p").before( $("#foo")[0] );
<p>I would like to say: </p><b id="foo">Hello</b>
<b id="foo">Hello</b><p>I would like to say: </p>
Inserts a jQuery object (similar to an Array of DOM Elements) before all paragraphs.
Introduz um objeto do jQuery (similar a uma disposição de elementos de DOM) antes de todos os parágrafos.
$("p").before( $("b") );
<p>I would like to say: </p><b>Hello</b>
<b>Hello</b><p>I would like to say: </p>
Clone matched DOM Elements and select the clones.
This is useful for moving copies of the elements to another location in the DOM.
Clone elementos combinados de DOM e selecionar clones. Isto é útil para mover cópias dos elementos para uma outra posição no DOM.
Clones all b elements (and selects the clones) and prepends them to all paragraphs.
Clona todos os elementos de b (e seleciona clones) e os introduz a todos os parágrafos.
$("b").clone().prependTo("p");
<b>Hello</b><p>, how are you?</p>
<b>Hello</b><p><b>Hello</b>, how are you?</p>
Removes all child nodes from the set of matched elements.
Remove todos os nós do jogo de elementos combinados.
$("p").empty()
<p>Hello, <span>Person</span> <a href="#">and person</a></p>
[ <p></p> ]
Insert all of the matched elements after another, specified, set of elements. This operation is, essentially, the reverse of doing a regular $(A).after(B), in that instead of inserting B after A, you're inserting A after B.
Introduzir todos os elementos combinados após outros, especificado, jogo dos elementos. Esta operação é, essencialmente, o reverso de fazer um $ regular (A) .Após(B), nisso em vez de introduzir B após A, você está introduzindo A após o B.
Same as $("#foo").after("p")
$("p").insertAfter("#foo");
<p>I would like to say: </p><div id="foo">Hello</div>
<div id="foo">Hello</div><p>I would like to say: </p>
Insert all of the matched elements before another, specified, set of elements. This operation is, essentially, the reverse of doing a regular $(A).before(B), in that instead of inserting B before A, you're inserting A before B.
Introduzir todos os elementos combinados antes de outros, especificado, jogo dos elementos. Esta operação é, essencialmente, o reverso de fazer um $ regular (A) .Após(B), nisso em vez de introduzir B antes de A, você está introduzindo A antes do B.
Same as $("#foo").before("p")
Mesmos que $ (“#foo”) .before (“p”)
$("p").insertBefore("#foo");
<div id="foo">Hello</div><p>I would like to say: </p>
<p>I would like to say: </p><div id="foo">Hello</div>
Prepend content to the inside of every matched element.
This operation is the best way to insert elements inside, at the beginning, of all matched elements.
Introduz o índice ao interior de cada elemento combinado. Esta operação é a mais melhor maneira introduzir para dentro elementos, no começo, de todos os elementos combinados.
Prepends some HTML to all paragraphs.
Prepends algum HTML a todos os parágrafos.
$("p").prepend("<b>Hello</b>");
<p>I would like to say: </p>
<p><b>Hello</b>I would like to say: </p>
Prepends an Element to all paragraphs.
Prepends um elemento a todos os parágrafos.
$("p").prepend( $("#foo")[0] );
<p>I would like to say: </p><b id="foo">Hello</b>
<p><b id="foo">Hello</b>I would like to say: </p>
Prepends a jQuery object (similar to an Array of DOM Elements) to all paragraphs.
Introduz um objeto do jQuery (similar a uma disposição de elementos de DOM) a todos os parágrafos.
$("p").prepend( $("b") );
<p>I would like to say: </p><b>Hello</b>
<p><b>Hello</b>I would like to say: </p>
Prepend all of the matched elements to another, specified, set of elements. This operation is, essentially, the reverse of doing a regular $(A).prepend(B), in that instead of prepending B to A, you're prepending A to B.
introduz todos os elementos combinados a outros, especificado, jogo dos elementos. Esta operação é, essencialmente, o reverso de fazer um $ regular (A) .introduz (B), nisso em vez de introduzir B a A, você introduz A a B.
Prepends all paragraphs to the element with the ID "foo"
Prepends todos os parágrafos ao elemento com o ID “foo”
$("p").prependTo("#foo");
<p>I would like to say: </p><div id="foo"><b>Hello</b></div>
<div id="foo"><p>I would like to say: </p><b>Hello</b></div>
Removes all matched elements from the DOM. This does NOT remove them from the jQuery object, allowing you to use the matched elements further. Can be filtered with an optional expressions.
Remove todos os elementos combinados do DOM. Isto não os remove do objeto do jQuery, permitindo que você use os elementos combinados mais. Podem ser filtradas com as expressões opcionais.
$("p").remove();
<p>Hello</p> how are <p>you?</p>
how are
$("p").remove(".hello");
<p class="hello">Hello</p> how are <p>you?</p>
how are <p>you?</p>
Wrap all matched elements with a structure of other elements. This wrapping process is most useful for injecting additional stucture into a document, without ruining the original semantic qualities of a document.
This works by going through the first element provided (which is generated, on the fly, from the provided HTML) and finds the deepest ancestor element within its structure - it is that element that will en-wrap everything else.
This does not work with elements that contain text. Any necessary text must be added after the wrapping is done.
Envolve todos os elementos combinados com uma estrutura de outros elementos. Este processo é o mais útil para injetar o elemento adicional em um original, sem arruinar as qualidades semânticas de um original. Isto trabalha atravessando o primeiro elemento fornecido (que é gerado, sobre o HTML fornecido) e achados o elemento o mais profundo do antepassado dentro de sua estrutura - é esse elemento que envolve tudo mais. Isto não trabalha com elementos que contêm o texto. Todo o texto necessário deve ser adicionado depois que envolver é feito.
$("p").wrap("<div class='wrap'></div>");
<p>Test Paragraph.</p>
<div class='wrap'><p>Test Paragraph.</p></div>
Wrap all matched elements with a structure of other elements. This wrapping process is most useful for injecting additional stucture into a document, without ruining the original semantic qualities of a document.
This works by going through the first element provided and finding the deepest ancestor element within its structure - it is that element that will en-wrap everything else.
This does not work with elements that contain text. Any necessary text must be added after the wrapping is done.
Envolver todos os elementos combinados com uma estrutura de outros elementos. Este processo é o mais útil para injetar o elemento adicional em um original, sem arruinar as qualidades semânticas de um original. Isto trabalha atravessando o primeiro elemento fornecido e encontrando o elemento o mais profundo do antepassado dentro de sua estrutura - é esse elemento que envolve tudo mais. Isto não trabalha com elementos que contêm o texto. Todo o texto necessário deve ser adicionado depois que envolver é feito.
$("p").wrap( document.getElementById('content') );
<p>Test Paragraph.</p><div id="content"></div>
<div id="content"><p>Test Paragraph.</p></div>
Adds more elements, matched by the given expression, to the set of matched elements.
Adiciona mais elementos, combinados pela expressão dada, ao jogo de elementos combinados.
$("p").add("span")
<p>Hello</p><span>Hello Again</span>
[ <p>Hello</p>, <span>Hello Again</span> ]
Adds more elements, created on the fly, to the set of matched elements.
Adiciona mais elementos, criados ao jogo de elementos combinados.
$("p").add("<span>Again</span>")
<p>Hello</p>
[ <p>Hello</p>, <span>Again</span> ]
Adds one or more Elements to the set of matched elements.
Adiciona um ou mais elemento ao jogo de elementos combinados.
$("p").add( document.getElementById("a") )
<p>Hello</p><p><span id="a">Hello Again</span></p>
[ <p>Hello</p>, <span id="a">Hello Again</span> ]
$("p").add( document.forms[0].elements )
<p>Hello</p><p><form><input/><button/></form>
[ <p>Hello</p>, <input/>, <button/> ]
Get a set of elements containing all of the unique children of each of the matched set of elements.
Can be filtered with an optional expressions.
Começar um jogo dos elementos que contêm todas as crianças originais de cada um do jogo combinado dos elementos. Podem ser filtradas com as expressões opcionais.
Find all children of each div.
Encontrar todas as crianças de cada div.
$("div").children()
<p>Hello</p><div><span>Hello Again</span></div><p>And Again</p>
[ <span>Hello Again</span> ]
Find all children with a class "selected" of each div.
Encontrar todas as crianças com uma classe “selecionada” de cada div.
$("div").children(".selected")
<div><span>Hello</span><p class="selected">Hello Again</p><p>And Again</p></div>
[ <p class="selected">Hello Again</p> ]
Filter the set of elements to those that contain the specified text.
Filtrar o jogo dos elementos àqueles que contêm o texto especificado.
$("p").contains("test")
<p>This is just a test.</p><p>So is this</p>
[ <p>This is just a test.</p> ]
End the most recent 'destructive' operation, reverting the list of matched elements back to its previous state. After an end operation, the list of matched elements will revert to the last state of matched elements.
If there was no destructive operation before, an empty set is returned.
Terminar a operação “destrutiva” a mais recente, revertendo a lista de elementos combinados para trás a seu estado precedente. Após uma operação do fim, a lista de elementos combinados reverte ao último estado de elementos combinados. Se não houver nenhuma operação destrutiva antes, um jogo vazio é retornado.
Selects all paragraphs, finds span elements inside these, and reverts the selection back to the paragraphs.
Seleciona todos os parágrafos, encontra elementos da extensão dentro destes, e reverte a seleção para trás aos parágrafos.
$("p").find("span").end();
<p><span>Hello</span>, how are you?</p>
[ <p>...</p> ]
Removes all elements from the set of matched elements that do not match the specified expression(s). This method is used to narrow down the results of a search.
Provide a comma-separated list of expressions to apply multiple filters at once.
Remove todos os elementos do jogo dos elementos combinados que não combinam as expressões especificadas. Este método é usado estreitar-se abaixo os resultados de uma busca. Fornecer uma lista vírgula-separada das expressões para aplicar filtros múltiplos em uma vez.
Selects all paragraphs and removes those without a class "selected".
Seleciona todos os parágrafos e remove aqueles sem uma classe “selecionada”.
$("p").filter(".selected")
<p class="selected">Hello</p><p>How are you?</p>
[ <p class="selected">Hello</p> ]
Selects all paragraphs and removes those without class "selected" and being the first one.
Seleciona todos os parágrafos e remove aqueles sem a classe “selecionada” e que é primeira.
$("p").filter(".selected, :first")
<p>Hello</p><p>Hello Again</p><p class="selected">And Again</p>
[ <p>Hello</p>, <p class="selected">And Again</p> ]
Removes all elements from the set of matched elements that do not pass the specified filter. This method is used to narrow down the results of a search.
Remove todos os elementos do jogo dos elementos combinados que não passam o filtro especificado. Este método é usado estreitar-se abaixo os resultados de uma busca.
Remove all elements that have a child ol element
Remover todos os elementos que têm um elemento do ol da criança
$("p").filter(function(index) {
return $("ol", this).length == 0;
})
<p><ol><li>Hello</li></ol></p><p>How are you?</p>
[ <p>How are you?</p> ]
Searches for all elements that match the specified expression. This method is a good way to find additional descendant elements with which to process.
All searching is done using a jQuery expression. The expression can be written using CSS 1-3 Selector syntax, or basic XPath.
Procura por todos os elementos que combinam a expressão especificada. Este método é uma maneira boa encontrar os elementos adicionais do descendente com que ao processo. Toda a procura é feita usando uma expressão do jQuery. A expressão pode ser escrita usando a sintaxe do seletor do CSS 1-3, ou XPath básico.
Starts with all paragraphs and searches for descendant span elements, same as $("p span")
Os começos com todos os parágrafos e as buscas para o descendente medem os elementos, mesmos que $ (de “a extensão p”)
$("p").find("span");
<p><span>Hello</span>, how are you?</p>
[ <span>Hello</span> ]
Checks the current selection against an expression and returns true, if at least one element of the selection fits the given expression.
Does return false, if no element fits or the expression is not valid.
filter(String) is used internally, therefore all rules that apply there apply here, too.
Verifica a seleção atual de encontro a uma expressão e retorna verdadeiro, se pelo menos um elemento da seleção couber a expressão dada. Retorna falso, se nenhum ajuste do elemento ou a expressão forem inválido. o filtro (corda) é usado internamente, conseqüentemente todas as réguas que se aplicam lá aplica-se aqui, demasiado.
Boolean
Returns true, because the parent of the input is a form element
Retorna verdadeiro, porque o pai da entrada é um elemento do formulário.
$("input[@type='checkbox']").parent().is("form")
<form><input type="checkbox" /></form>
true
Returns false, because the parent of the input is a p element
Retorna falso, porque o pai da entrada é um elemento de p.
$("input[@type='checkbox']").parent().is("form")
<form><p><input type="checkbox" /></p></form>
false
Get a set of elements containing the unique next siblings of each of the matched set of elements.
It only returns the very next sibling, not all next siblings.
Can be filtered with an optional expressions.
Começar um jogo dos elementos que contêm as irmãs originais de cada um do jogo combinado dos elementos. Retorna somente a irmã seguinte, não todas as irmãs seguintes. Podem ser filtradas com as expressões opcionais.
Find the very next sibling of each paragraph.
Encontrar a irmã seguinte de cada parágrafo.
$("p").next()
<p>Hello</p><p>Hello Again</p><div><span>And Again</span></div>
[ <p>Hello Again</p>, <div><span>And Again</span></div> ]
Find the very next sibling of each paragraph that has a class "selected".
Encontrar a irmã seguinte de cada parágrafo que tem uma classe “selecionada”.
$("p").next(".selected")
<p>Hello</p><p class="selected">Hello Again</p><div><span>And Again</span></div>
[ <p class="selected">Hello Again</p> ]
Removes the specified Element from the set of matched elements. This method is used to remove a single Element from a jQuery object.
Remove o elemento especificado do jogo de elementos combinados. Este método é usado remover um único elemento de um objeto do jQuery.
Removes the element with the ID "selected" from the set of all paragraphs.
Remove o elemento com o ID “selecionado” do jogo de todos os parágrafos.
$("p").not( $("#selected")[0] )
<p>Hello</p><p id="selected">Hello Again</p>
[ <p>Hello</p> ]
Removes elements matching the specified expression from the set of matched elements. This method is used to remove one or more elements from a jQuery object.
Remove os elementos que combinam a expressão especificada do jogo de elementos combinados. Este método é usado remover um ou mais elemento de um jQuery objeta.
Removes the element with the ID "selected" from the set of all paragraphs.
Remove o elemento com o ID “selecionado” do jogo de todos os parágrafos.
$("p").not("#selected")
<p>Hello</p><p id="selected">Hello Again</p>
[ <p>Hello</p> ]
Removes any elements inside the array of elements from the set of matched elements. This method is used to remove one or more elements from a jQuery object.
Remove todos os elementos dentro da disposição dos elementos do jogo de elementos combinados. Este método é usado remover um ou mais elemento de um jQuery objeta.
Removes all elements that match "div p.selected" from the total set of all paragraphs.
Remove todos os elementos que combinam “div p.selected” do jogo total de todos os parágrafos.
$("p").not( $("div p.selected") )
<div><p>Hello</p><p class="selected">Hello Again</p></div>
[ <p>Hello</p> ]
Get a set of elements containing the unique parents of the matched set of elements.
Can be filtered with an optional expressions.
Começar um jogo dos elementos que contêm os pais originais do jogo combinado dos elementos. Podem ser filtradas com as expressões opcionais.
Find the parent element of each paragraph.
Encontrar o elemento do pai de cada parágrafo.
$("p").parent()
<div><p>Hello</p><p>Hello</p></div>
[ <div><p>Hello</p><p>Hello</p></div> ]
Find the parent element of each paragraph with a class "selected".
Encontrar o elemento do pai de cada parágrafo com uma classe “selecionada”.
$("p").parent(".selected")
<div><p>Hello</p></div><div class="selected"><p>Hello Again</p></div>
[ <div class="selected"><p>Hello Again</p></div> ]
Get a set of elements containing the unique ancestors of the matched set of elements (except for the root element).
Can be filtered with an optional expressions.
Começar um jogo dos elementos que contêm os antecessores originais do jogo combinado dos elementos (à exceção do elemento da raiz). Podem ser filtradas com as expressões opcionais.
Find all parent elements of each span.
Encontrar todos os elementos do pai de cada extensão.
$("span").parents()
<html><body><div><p><span>Hello</span></p><span>Hello Again</span></div></body></html>
[ <body>...</body>, <div>...</div>, <p><span>Hello</span></p> ]
Find all parent elements of each span that is a paragraph.
Encontrar todos os elementos do pai de cada extensão que é um parágrafo.
$("span").parents("p")
<html><body><div><p><span>Hello</span></p><span>Hello Again</span></div></body></html>
[ <p><span>Hello</span></p> ]
Get a set of elements containing the unique previous siblings of each of the matched set of elements.
Can be filtered with an optional expressions.
It only returns the immediately previous sibling, not all previous siblings.
Começar um jogo dos elementos que contêm as irmãs precedentes originais de cada um do jogo combinado dos elementos. Podem ser filtradas com as expressões opcionais. Retorna somente a irmã imediatamente precedente, não todas as irmãs precedentes.
Find the very previous sibling of each paragraph.
Encontrar o sibling muito precedente de cada parágrafo.
$("p").prev()
<p>Hello</p><div><span>Hello Again</span></div><p>And Again</p>
[ <div><span>Hello Again</span></div> ]
Find the very previous sibling of each paragraph that has a class "selected".
Encontrar a irmã precedente de cada parágrafo que tem uma classe “selecionada”.
$("p").prev(".selected")
<div><span>Hello</span></div><p class="selected">Hello Again</p><p>And Again</p>
[ <div><span>Hello</span></div> ]
Get a set of elements containing all of the unique siblings of each of the matched set of elements.
Can be filtered with an optional expressions.
Começar um jogo dos elementos que contêm todos as irmãs originais de cada um do jogo combinado dos elementos. Podem ser filtradas com as expressões opcionais.
Find all siblings of each div.
Encontrar todos os siblings de cada div.
$("div").siblings()
<p>Hello</p><div><span>Hello Again</span></div><p>And Again</p>
[ <p>Hello</p>, <p>And Again</p> ]
Find all siblings with a class "selected" of each div.
Encontrar todos os siblings com uma classe “selecionada” de cada div.
$("div").siblings(".selected")
<div><span>Hello</span></div><p class="selected">Hello Again</p><p>And Again</p>
[ <p class="selected">Hello Again</p> ]
Access a style property on the first matched element. This method makes it easy to retrieve a style property value from the first matched element.
Alcança uma propriedade do estilo no primeiro elemento combinado. Este método facilmente recupera um valor da propriedade do estilo do primeiro elemento combinado.
String
Retrieves the color style of the first paragraph
Recupera o estilo da cor do primeiro parágrafo.
$("p").css("color");
<p style="color:red;">Test Paragraph.</p>
"red"
Retrieves the font-weight style of the first paragraph.
Recupera o font-weight estilo do primeiro parágrafo.
$("p").css("font-weight");
<p style="font-weight: bold;">Test Paragraph.</p>
"bold"
Set a key/value object as style properties to all matched elements.
Ajustar um objeto da chave/valor como propriedades do estilo a todos os elementos combinados.
This serves as the best way to set a large number of style properties
Isto serve como a melhor maneira para ajustar um grande número propriedades do estilo em todos os elementos combinados.
Sets color and background styles to all p elements.
Ajusta estilos da cor e do fundo a todos os elementos de p.
$("p").css({ color: "red", background: "blue" });
<p>Test Paragraph.</p>
<p style="color:red; background:blue;">Test Paragraph.</p>
Set a single style property to a value, on all matched elements. If a number is provided, it is automatically converted into a pixel value.
Ajustar uma única propriedade do estilo a um valor, em todos os elementos combinados.Se um número for fornecido, será convertido automaticamente em um valor de pixel.
Changes the color of all paragraphs to red
Muda a cor de todos os parágrafos para vermelho
$("p").css("color","red");
<p>Test Paragraph.</p>
<p style="color:red;">Test Paragraph.</p>
Changes the left of all paragraphs to "30px"
Muda a esquerda de todos os parágrafos a “30px”.
$("p").css("left",30);
<p>Test Paragraph.</p>
<p style="left:30px;">Test Paragraph.</p>
Get the current computed, pixel, height of the first matched element.
Captura altura atual, pixel, altura do primeiro elemento combinado.
String
$("p").height();
<p>This is just a test.</p>
300
Set the CSS width of every matched element. If no explicit unit was specified (like 'em' or '%') then "px" is added to the width.
Ajustar a largura do CSS de cada elemento combinado. Se nenhuma unidade explícita for especificada (like 'em' or '%') então o “px” é adicionado à largura.
$("p").height(20);
<p>This is just a test.</p>
<p style="height:20px;">This is just a test.</p>
$("p").height("20em");
<p>This is just a test.</p>
<p style="height:20em;">This is just a test.</p>
Get the current computed, pixel, width of the first matched element.
Captura a largura atual, pixel, largura do primeiro elemento combinado.
String
$("p").width();
<p>This is just a test.</p>
300
Set the CSS width of every matched element. If no explicit unit was specified (like 'em' or '%') then "px" is added to the width.
Ajustar a largura do CSS de cada elemento combinado. Se nenhuma unidade explícita for especificada (like 'em' or '%') então o “px” é adicionado à largura.
$("p").width(20);
<p>This is just a test.</p>
<p style="width:20px;">This is just a test.</p>
$("p").width("20em");
<p>This is just a test.</p>
<p style="width:20em;">This is just a test.</p>
Contains flags for the useragent, read from navigator.userAgent. Available flags are: safari, opera, msie, mozilla
This property is available before the DOM is ready, therefore you can use it to add ready events only for certain browsers.
There are situations where object detections is not reliable enough, in that cases it makes sense to use browser detection. Simply try to avoid both!
A combination of browser and object detection yields quite reliable results.
Boolean
Returns true if the current useragent is some version of microsoft's internet explorer
$.browser.msie
Alerts "this is safari!" only for safari browsers
if($.browser.safari) { $( function() { alert("this is safari!"); } ); }
A generic iterator function, which can be used to seemlessly iterate over both objects and arrays. This function is not the same as $().each() - which is used to iterate, exclusively, over a jQuery object. This function can be used to iterate over anything.
The callback has two arguments:the key (objects) or index (arrays) as first the first, and the value as the second.
Object
This is an example of iterating over the items in an array, accessing both the current item and its index.
$.each( [0,1,2], function(i, n){
alert( "Item #" + i + ": " + n );
});
This is an example of iterating over the properties in an Object, accessing both the current item and its key.
$.each( { name: "John", lang: "JS" }, function(i, n){
alert( "Name: " + i + ", Value: " + n );
});
Extend one object with one or more others, returning the original, modified, object. This is a great utility for simple inheritance.
Object
Merge settings and options, modifying settings
var settings = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };
jQuery.extend(settings, options);
settings == { validate: true, limit: 5, name: "bar" }
Merge defaults and options, without modifying the defaults
var defaults = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };
var settings = jQuery.extend({}, defaults, options);
settings == { validate: true, limit: 5, name: "bar" }
Filter items out of an array, by using a filter function.
The specified function will be passed two arguments: The current array item and the index of the item in the array. The function must return 'true' to keep the item in the array, false to remove it.
Array
$.grep( [0,1,2], function(i){
return i > 0;
});
[1, 2]
Translate all items in an array to another array of items.
The translation function that is provided to this method is called for each item in the array and is passed one argument: The item to be translated.
The function can then return the translated value, 'null' (to remove the item), or an array of values - which will be flattened into the full array.
Array
Maps the original array to a new one and adds 4 to each value.
$.map( [0,1,2], function(i){
return i + 4;
});
[4, 5, 6]
Maps the original array to a new one and adds 1 to each value if it is bigger then zero, otherwise it's removed-
$.map( [0,1,2], function(i){
return i > 0 ? i + 1 : null;
});
[2, 3]
Maps the original array to a new one, each element is added with it's original value and the value plus one.
$.map( [0,1,2], function(i){
return [ i, i + 1 ];
});
[0, 1, 1, 2, 2, 3]
Merge two arrays together, removing all duplicates.
The result is the altered first argument with the unique elements from the second array added.
Array
Merges two arrays, removing the duplicate 2
$.merge( [0,1,2], [2,3,4] )
[0,1,2,3,4]
Merges two arrays, removing the duplicates 3 and 2
var array = [3,2,1]; $.merge( array, [4,3,2] )
array == [3,2,1,4]
Remove the whitespace from the beginning and end of a string.
String
$.trim(" hello, how are you? ");
"hello, how are you?"
Binds a handler to a particular event (like click) for each matched element. The event handler is passed an event object that you can use to prevent default behaviour. To stop both default action and event bubbling, your handler has to return false.
In most cases, you can define your event handlers as anonymous functions (see first example). In cases where that is not possible, you can pass additional data as the second paramter (and the handler function as the third), see second example.
$("p").bind("click", function(){
alert( $(this).text() );
});
<p>Hello</p>
alert("Hello")
Pass some additional data to the event handler.
function handler(event) {
alert(event.data.foo);
}
$("p").bind("click", {foo: "bar"}, handler)
alert("bar")
Cancel a default action and prevent it from bubbling by returning false from your function.
$("form").bind("submit", function() { return false; })
Cancel only the default action by using the preventDefault method.
$("form").bind("submit", function(event){
event.preventDefault();
});
Stop only an event from bubbling by using the stopPropagation method.
$("form").bind("submit", function(event){
event.stopPropagation();
});
Trigger the blur event of each matched element. This causes all of the functions that have been bound to thet blur event to be executed.
Note: This does not execute the blur method of the underlying elements! If you need to blur an element via code, you have to use the DOM method, eg. $("#myinput")[0].blur();
$("p").blur();
<p onblur="alert('Hello');">Hello</p>
alert('Hello');
Bind a function to the blur event of each matched element.
$("p").blur( function() { alert("Hello"); } );
<p>Hello</p>
<p onblur="alert('Hello');">Hello</p>
Bind a function to the change event of each matched element.
$("p").change( function() { alert("Hello"); } );
<p>Hello</p>
<p onchange="alert('Hello');">Hello</p>
Trigger the click event of each matched element. This causes all of the functions that have been bound to thet click event to be executed.
$("p").click();
<p onclick="alert('Hello');">Hello</p>
alert('Hello');
Bind a function to the click event of each matched element.
$("p").click( function() { alert("Hello"); } );
<p>Hello</p>
<p onclick="alert('Hello');">Hello</p>
Bind a function to the dblclick event of each matched element.
$("p").dblclick( function() { alert("Hello"); } );
<p>Hello</p>
<p ondblclick="alert('Hello');">Hello</p>
Bind a function to the error event of each matched element.
$("p").error( function() { alert("Hello"); } );
<p>Hello</p>
<p onerror="alert('Hello');">Hello</p>
Trigger the focus event of each matched element. This causes all of the functions that have been bound to thet focus event to be executed.
Note: This does not execute the focus method of the underlying elements! If you need to focus an element via code, you have to use the DOM method, eg. $("#myinput")[0].focus();
$("p").focus();
<p onfocus="alert('Hello');">Hello</p>
alert('Hello');
Bind a function to the focus event of each matched element.
$("p").focus( function() { alert("Hello"); } );
<p>Hello</p>
<p onfocus="alert('Hello');">Hello</p>
A method for simulating hovering (moving the mouse on, and off, an object). This is a custom method which provides an 'in' to a frequent task.
Whenever the mouse cursor is moved over a matched element, the first specified function is fired. Whenever the mouse moves off of the element, the second specified function fires. Additionally, checks are in place to see if the mouse is still within the specified element itself (for example, an image inside of a div), and if it is, it will continue to 'hover', and not move out (a common error in using a mouseout event handler).
$("p").hover(function(){
$(this).addClass("over");
},function(){
$(this).addClass("out");
});
Bind a function to the keydown event of each matched element.
$("p").keydown( function() { alert("Hello"); } );
<p>Hello</p>
<p onkeydown="alert('Hello');">Hello</p>
Bind a function to the keypress event of each matched element.
$("p").keypress( function() { alert("Hello"); } );
<p>Hello</p>
<p onkeypress="alert('Hello');">Hello</p>
Bind a function to the keyup event of each matched element.
$("p").keyup( function() { alert("Hello"); } );
<p>Hello</p>
<p onkeyup="alert('Hello');">Hello</p>
Bind a function to the load event of each matched element.
$("p").load( function() { alert("Hello"); } );
<p>Hello</p>
<p onload="alert('Hello');">Hello</p>
Bind a function to the mousedown event of each matched element.
$("p").mousedown( function() { alert("Hello"); } );
<p>Hello</p>
<p onmousedown="alert('Hello');">Hello</p>
Bind a function to the mousemove event of each matched element.
$("p").mousemove( function() { alert("Hello"); } );
<p>Hello</p>
<p onmousemove="alert('Hello');">Hello</p>
Bind a function to the mouseout event of each matched element.
$("p").mouseout( function() { alert("Hello"); } );
<p>Hello</p>
<p onmouseout="alert('Hello');">Hello</p>
Bind a function to the mouseover event of each matched element.
$("p").mouseover( function() { alert("Hello"); } );
<p>Hello</p>
<p onmouseover="alert('Hello');">Hello</p>
Bind a function to the mouseup event of each matched element.
$("p").mouseup( function() { alert("Hello"); } );
<p>Hello</p>
<p onmouseup="alert('Hello');">Hello</p>
Binds a handler to a particular event (like click) for each matched element. The handler is executed only once for each element. Otherwise, the same rules as described in bind() apply. The event handler is passed an event object that you can use to prevent default behaviour. To stop both default action and event bubbling, your handler has to return false.
In most cases, you can define your event handlers as anonymous functions (see first example). In cases where that is not possible, you can pass additional data as the second paramter (and the handler function as the third), see second example.
$("p").one("click", function(){
alert( $(this).text() );
});
<p>Hello</p>
alert("Hello")
Bind a function to be executed whenever the DOM is ready to be traversed and manipulated. This is probably the most important function included in the event module, as it can greatly improve the response times of your web applications.
In a nutshell, this is a solid replacement for using window.onload, and attaching a function to that. By using this method, your bound Function will be called the instant the DOM is ready to be read and manipulated, which is exactly what 99.99% of all Javascript code needs to run.
There is one argument passed to the ready event handler: A reference to the jQuery function. You can name that argument whatever you like, and can therefore stick with the $ alias without risc of naming collisions.
Please ensure you have no code in your <body> onload event handler, otherwise $(document).ready() may not fire.
You can have as many $(document).ready events on your page as you like. The functions are then executed in the order they were added.
$(document).ready(function(){ Your code here... });
Uses both the shortcut for $(document).ready() and the argument to write failsafe jQuery code using the $ alias, without relying on the global alias.
jQuery(function($) {
// Your code using failsafe $ alias here...
});
Bind a function to the resize event of each matched element.
$("p").resize( function() { alert("Hello"); } );
<p>Hello</p>
<p onresize="alert('Hello');">Hello</p>
Bind a function to the scroll event of each matched element.
$("p").scroll( function() { alert("Hello"); } );
<p>Hello</p>
<p onscroll="alert('Hello');">Hello</p>
Trigger the select event of each matched element. This causes all of the functions that have been bound to thet select event to be executed.
$("p").select();
<p onselect="alert('Hello');">Hello</p>
alert('Hello');
Bind a function to the select event of each matched element.
$("p").select( function() { alert("Hello"); } );
<p>Hello</p>
<p onselect="alert('Hello');">Hello</p>
Trigger the submit event of each matched element. This causes all of the functions that have been bound to thet submit event to be executed.
Note: This does not execute the submit method of the form element! If you need to submit the form via code, you have to use the DOM method, eg. $("form")[0].submit();
Triggers all submit events registered for forms, but does not submit the form
$("form").submit();
Bind a function to the submit event of each matched element.
Prevents the form submission when the input has no value entered.
$("#myform").submit( function() {
return $("input", this).val().length > 0;
} );
<form id="myform"><input /></form>
Toggle between two function calls every other click. Whenever a matched element is clicked, the first specified function is fired, when clicked again, the second is fired. All subsequent clicks continue to rotate through the two functions.
Use unbind("click") to remove.
$("p").toggle(function(){
$(this).addClass("selected");
},function(){
$(this).removeClass("selected");
});
Trigger a type of event on every matched element.
$("p").trigger("click")
<p click="alert('hello')">Hello</p>
alert('hello')
The opposite of bind, removes a bound event from each of the matched elements.
Without any arguments, all bound events are removed.
If the type is provided, all bound events of that type are removed.
If the function that was passed to bind is provided as the second argument, only that specific event handler is removed.
$("p").unbind()
<p onclick="alert('Hello');">Hello</p>
[ <p>Hello</p> ]
$("p").unbind( "click" )
<p onclick="alert('Hello');">Hello</p>
[ <p>Hello</p> ]
$("p").unbind( "click", function() { alert("Hello"); } )
<p onclick="alert('Hello');">Hello</p>
[ <p>Hello</p> ]
Bind a function to the unload event of each matched element.
$("p").unload( function() { alert("Hello"); } );
<p>Hello</p>
<p onunload="alert('Hello');">Hello</p>
A function for making your own, custom, animations. The key aspect of this function is the object of style properties that will be animated, and to what end. Each key within the object represents a style property that will also be animated (for example: "height", "top", or "opacity").
The value associated with the key represents to what end the property will be animated. If a number is provided as the value, then the style property will be transitioned from its current state to that new number. Oterwise if the string "hide", "show", or "toggle" is provided, a default animation will be constructed for that property.
$("p").animate({
height: 'toggle', opacity: 'toggle'
}, "slow");
$("p").animate({
left: 50, opacity: 'show'
}, 500);
An example of using an 'easing' function to provide a different style of animation. This will only work if you have a plugin that provides this easing function (Only 'linear' is provided by default, with jQuery).
$("p").animate({
opacity: 'show'
}, "slow", "easein");
Fade in all matched elements by adjusting their opacity and firing an optional callback after completion.
Only the opacity is adjusted for this animation, meaning that all of the matched elements should already have some form of height and width associated with them.
$("p").fadeIn("slow");
$("p").fadeIn("slow",function(){
alert("Animation Done.");
});
Fade out all matched elements by adjusting their opacity and firing an optional callback after completion.
Only the opacity is adjusted for this animation, meaning that all of the matched elements should already have some form of height and width associated with them.
$("p").fadeOut("slow");
$("p").fadeOut("slow",function(){
alert("Animation Done.");
});
Fade the opacity of all matched elements to a specified opacity and firing an optional callback after completion.
Only the opacity is adjusted for this animation, meaning that all of the matched elements should already have some form of height and width associated with them.
$("p").fadeTo("slow", 0.5);
$("p").fadeTo("slow", 0.5, function(){
alert("Animation Done.");
});
Hides each of the set of matched elements if they are shown.
$("p").hide()
<p>Hello</p>
[ <p style="display: none">Hello</p> ]
Hide all matched elements using a graceful animation and firing an optional callback after completion.
The height, width, and opacity of each of the matched elements are changed dynamically according to the specified speed.
$("p").hide("slow");
$("p").hide("slow",function(){
alert("Animation Done.");
});
Displays each of the set of matched elements if they are hidden.