Los mejores ejemplos de jQuery

jQuery es la biblioteca de JavaScript más utilizada y se utiliza en más de la mitad de los principales sitios web. Su lema es "¡escribe menos, haz más ...!"

jQuery facilita el uso del desarrollo web al proporcionar una serie de funciones de "ayuda". Estos ayudan a los desarrolladores a escribir rápidamente interacciones DOM (Document Object Model) sin necesidad de escribir manualmente tanto JavaScript.

jQuery agrega una variable global con todos los métodos de bibliotecas adjuntos. La convención de nomenclatura es tener esta variable global como $. escribiendo $.tienes todos los métodos de jQuery a tu disposición.

Empezando

Hay dos formas principales de comenzar a usar jQuery:

  • Incluya jQuery localmente : descargue la biblioteca jQuery de jquery.com e inclúyala en su código HTML.
  • Use un CDN : enlace a la biblioteca jQuery usando un CDN (Content Delivery Network).

Selectores

jQuery usa selectores de estilo CSS para seleccionar partes o elementos de una página HTML. Luego le permite hacer algo con los elementos usando métodos o funciones jQuery.

Para utilizar uno de estos selectores, escriba un signo de dólar y paréntesis después de que: $(). Esta es la abreviatura de la jQuery()función. Dentro de los paréntesis, agregue el elemento que desea seleccionar. Puede utilizar comillas simples o dobles. Después de esto, agregue un punto después del paréntesis y el método que desea utilizar.

En jQuery, los selectores de clase e ID son como los de CSS.

Aquí hay un ejemplo de un método jQuery que selecciona todos los elementos de párrafo y les agrega una clase de "seleccionados":

This is a paragraph selected by a jQuery method.

This is also a paragraph selected by a jQuery method.

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

En jQuery, los selectores de clase e ID son los mismos que en CSS. Si desea seleccionar elementos con una determinada clase, utilice un punto ( .) y el nombre de la clase. Si desea seleccionar elementos con un ID determinado, utilice el símbolo de almohadilla ( #) y el nombre del ID. Tenga en cuenta que HTML no distingue entre mayúsculas y minúsculas, por lo que es recomendable mantener el marcado HTML y los selectores de CSS en minúsculas.

Seleccionar por clase

Si desea seleccionar elementos con una determinada clase, utilice un punto (.) Y el nombre de la clase.

Paragraph with a class.

$(".pWithClass").css("color", "blue"); // colors the text blue

También puede usar el selector de clases en combinación con un nombre de etiqueta para ser más específico.

    My Wish List
`

$("ul.wishList").append("
  • New blender
  • ");

    Seleccionar por ID

    Si desea seleccionar elementos con un determinado valor de ID, utilice el símbolo de almohadilla (#) y el nombre de ID.

  • List item with an ID.
  • $("#liWithID").replaceWith("

    Socks

    ");

    Al igual que con el selector de clases, también se puede utilizar en combinación con un nombre de etiqueta.

    News Headline

    $("h1#headline").css("font-size", "2em");

    Seleccionar por valor de atributo

    Si desea seleccionar elementos con un determinado atributo, utilice ([attributeName="value"]).

    $("[name='myInput']").value("Test"); // sets input value to "Test"

    También puede utilizar el selector de atributos en combinación con un nombre de etiqueta para ser más específico.

    `

    Button

    $("input[name='myElement']").remove(); // removes the input field not the button

    Selectores que actúan como filtros

    También hay selectores que actúan como filtros; por lo general, comienzan con dos puntos. Por ejemplo, el :firstselector selecciona el elemento que es el primer hijo de su padre. A continuación, se muestra un ejemplo de una lista desordenada con algunos elementos de la lista. El selector de jQuery debajo de la lista selecciona el primero

  • elemento en la lista - el elemento de lista "Uno" - y luego usa el .cssmétodo para convertir el texto en verde.

    • One
    • Two
    • Three
    $("li:first").css("color", "green");

    Selector de atributos

    Hay selectores que devuelven elementos que coinciden con determinadas combinaciones de Atributos, como el atributo contiene , el atributo termina con , el atributo comienza con, etc. Aquí hay un ejemplo de una lista desordenada con algunos elementos de la lista. El selector de jQuery debajo de la lista selecciona el

  • elemento en la lista - el elemento de lista "Uno" ya que tiene un data*atributo "India"como su valor - y luego usa el .cssmétodo para convertir el texto en verde.

    • Mumbai
    • Beijing
    • New York
    $("li[data-country='India']").css("color", "green");

    Otro selector de filtrado :contains(text), selecciona elementos que tienen un texto determinado. Coloque el texto que desea hacer coincidir entre paréntesis. Aquí tienes un ejemplo con dos párrafos. El selector de jQuery toma la palabra "Moto" y cambia su color a amarillo.

    Hello

    World

    $("p:contains('World')").css("color", "yellow");

    De manera similar, el :lastselector selecciona el elemento que es el último hijo de su padre. El selector de jQuery a continuación selecciona el último

  • Original text


  • elemento en la lista - el elemento de lista "Tres" - y luego usa el .cssmétodo para convertir el texto en amarillo.

    $("li:last").css("color", "yellow");

    Nota: En el selector de jQuery,Worldestá entre comillas simples porque ya está dentro de un par de comillas dobles. Utilice siempre comillas simples dentro de comillas dobles para evitar terminar una cadena sin querer.

    Selectores múltiples

    En jQuery, puede usar múltiples selectores para aplicar los mismos cambios a más de un elemento, usando una sola línea de código. Haz esto separando los diferentes identificadores con una coma. Por ejemplo, si desea establecer el color de fondo de tres elementos con los identificadores gato, perro y rata respectivamente en rojo, simplemente haga:

    $("#cat,#dog,#rat").css("background-color","red");

    Método HTML

    The jQuery .html() method gets the content of a HTML element or sets the content of an HTML element.

    Getting

    To return the content of a HTML element, use this syntax:

    $('selector').html();

    For example:

    $('#example').html();

    Setting

    To set the content of a HTML element, use this syntax:

    $('selector').html(content);

    For example:

    $('p').html('Hello World!');

    That will set the content of all of the

    Warning

    .html() method is used to set the element's content in HTML format. This may be dangerous if the content is provided by user. Consider using .text() method instead if you need to set non-HTML strings as content.

    CSS Method

    The jQuery .css() method gets the value of a computed style property for the first element in the set of matched elements or set one or more CSS properties for every matched element.

    Getting

    To return the value of a specified CSS property, use the following syntax:

     $(selector).css(propertyName);

    Example:

     $('#element').css('background');

    Note: Here we can use any css selector eg: element(HTML Tag selector), .element(Class Selector), #element(ID selector).

    Setting

    To set a specified CSS property, use the following syntax:

     $(selector).css(propertyName,value);

    Example:

     $('#element').css('background','red');

    To set multiple CSS properties, you'll have to use the object literal syntax like this:

     $('#element').css({ 'background': 'gray', 'color': 'white' });

    If you want to change a property labeled with more than one word, refer to this example:

    To change background-color of an element

     $('#element').css('background-color', 'gray');

    Click Method

    The jQuery Click method triggers a function when an element is clicked. The function is known as a "handler" because it handles the click event. Functions can impact the HTML element that is bound to the click using the jQuery Click method, or they can change something else entirely. The most-used form is:

    $("#clickMe").click(handler)

    The click method takes the handler function as an argument and executes it every time the element #clickMe is clicked. The handler function receives a parameter known as an eventObject that can be useful for controlling the action.

    Examples

    This code shows an alert when a user clicks a button:

    Click Here
    $("#alert").click(function () { alert("Hi! I'm an alert"); });

    The eventObject has some built in methods, including preventDefault(), which does exactly what it says - stops the default event of an element. Here we pevent the anchor tag from acting as a link:

    Link to Google
    $("#myLink").click(function (event) { event.preventDefault(); });

    More ways to play with the click method

    The handler function can also accept additional data in the form of an object:

    jqueryElement.click(usefulInfo, handler)

    The data can be of any type.

    $("element").click({firstWord: "Hello", secondWord: "World"}, function(event){ alert(event.data.firstWord); alert(event.data.secondWord); });

    Invoking the click method without a handler function triggers a click event:

    $("#alert").click(function () { alert("Hi! I'm an alert"); }); $("#alert").click();

    Now, whenever the page loads, the click event will be triggered when we enter or reload the page, and show the assigned alert.

    Also you should prefer to use .on("click",...) over .click(...) because the former can use less memory and work for dynamically added elements.

    Common Mistakes

    The click event is only bound to elements currently in the DOM at the time of binding, so any elements added afterwards will not be bound. To bind all elements in the DOM, even if they will be created at a later time, use the .on() method.

    For example, this click method example:

    $("element").click(function() { alert("I've been clicked!"); });

    Can be changed to this on method example:

    $(document).on("click", "element", function() { alert("I've been clicked!"); });

    Getting The Element From A Click event

    This applies to both jQuery and plain JavaScript, but if you set up your event trigger to target a class, you can grab the specific element that triggered the element by using the this keyword.

    jQuery happens to make it very easy (and multi browser friendly) to traverse the DOM to find that element's parents, siblings, and children, as well.

    Let's say I have a table full of buttons and I want to target the row that button is in, I can simply wrap this in a jQuery selector and then get its parent and its parent's parent like so:

    $( document ).on("click", ".myCustomBtnClassInATable", function () { var myTableCell = $(this).parent(); var myTableRow = myTableCell.parent(); var myTableBody = myTableRow.parent(); var myTable = myTableBody.parent(); //you can also chain these all together to get what you want in one line var myTableBody = $(this).parent().parent().parent(); });

    It is also interesting to check out the event data for the click event, which you can grab by passing in any variable name to the function in the click event. You'll most likely see an e or event in most cases:

    $( document ).on("click", ".myCustomBtnClassInATable", function (e) { //find out more information about the event variable in the console console.log(e); });

    Mousedown Method

    The mousedown event occurs when the left mouse button is pressed. To trigger the mousedown event for the selected element, use this syntax: $(selector).mousedown();

    Most of the time, however, the mousedown method is used with a function attached to the mousedown event. Here's the syntax: $(selector).mousedown(function); For example:

    $(#example).mousedown(function(){ alert("Example was clicked"); });

    That code will make the page alert "Example was clicked" when #example is clicked.

    Hover Method

    The jquery hover method is a combination of the mouseenter and mouseleave events. The syntax is this:

    $(selector).hover(inFunction, outFunction);

    The first function, inFunction, will run when the mouseenter event occurs. The second function is optional, but will run when the mouseleave event occurs. If only one function is specified, the other function will run for both the mouseenter and mouseleave events. Below is a more specific example.

    $("p").hover(function(){ $(this).css("background-color", "yellow"); }, function(){ $(this).css("background-color", "pink"); });

    So this means that hover on paragraph will change its background color to yellow and the opposite will change back to pink.

    Animate Method

    jQuery's animate method makes it easy to create simple animations using only a few lines of code. The basic structure is as following:

    $(".selector").animate(properties, duration, callbackFunction());

    For the properties argument, you need to pass a javascript object with the CSS properties you want to animate as keys and the values you want to animate to as values. For the duration, you need to input the amount of time in milliseconds the animation should take. The callbackFunction() is executed once the animation has finished.

    Example

    A simple example would look like this:

    $(".awesome-animation").animate({ opacity: 1, bottom: += 15 }, 1000, function() { $(".different-element").hide(); });

    Hide Method

    In its simplest form, .hide() hides the matched element immediately, with no animation. For example:

    $(".myclass").hide()

    will hide all the elements whose class is myclass. Any jQuery selector can be used.

    .hide() as an animation method

    Thanks to its options, .hide() can animate the width, height, and opacity of the matched elements simultaneously.

    • Duration can be provided in milliseconds, or using the literals slow (600 ms) and fast(200ms). for example:
    • A function can be specified to be called once the animation is complete, once per every matched element. This callback is mainly useful for chaining together different animations. For example
    $("#myobject").hide(800)
    $("p").hide( "slow", function() { $(".titles").hide("fast"); alert("No more text!"); });

    Show Method

    In its simplest form, .show() displays the matched element immediately, with no animation. For example:

    $(".myclass").show();

    will show all the elements whose class is myclass. Any jQuery selector can be used.

    However, this method does not override !important in the CSS style, such as display: none !important.

    .show() as an animation method

    Thanks to its options, .show() can animate the width, height, and opacity of the matched elements simultaneously.

    • Duration can be provided in milliseconds, or using the literals slow (600 ms) and fast(200ms). for example:
    • A function can be specified to be called once the animation is complete, once per every matched element. for example
    $("#myobject").show("slow");
    $("#title").show( "slow", function() { $("p").show("fast"); });

    jQuery Toggle method

    To show / hide elements you can use toggle() method. If element is hidden toggle() will show it and vice versa. Usage:

    $(".myclass").toggle()

    Slide Down method

    This method animates the height of the matched elements. This causes lower parts of the page to slide down, making way for the revealed items. Usage:

    $(".myclass").slideDown(); //will expand the element with the identifier myclass for 400 ms. $(".myclass").slideDown(1000); //will expand the element with the identifier myclass for 1000 ms. $(".myclass").slideDown("slow"); //will expand the element with the identifier myclass for 600 ms. $(".myclass").slideDown("fast"); //will expand the element with the identifier myclass for 200 ms.

    Load Method

    The load() method loads data from a server and puts the returned data into the selected element.

    Note: There is also a jQuery Event method called load. Which one is called, depends on the parameters.

    Example

    $("button").click(function(){ $("#div1").load("demo_test.txt"); });

    Chaining

    jQuery chaining allows you to execute multiple methods on the same jQuery selection, all on a single line.

    Chaining allows us to turn multi-line statements:

    $('#someElement').removeClass('classA'); $('#someElement').addClass('classB');

    Into a single statement:

    $('#someElement').removeClass('classA').addClass('classB');

    Ajax Get Method

    Sends an asynchronous http GET request to load data from the server. Its general form is:

    jQuery.get( url [, data ] [, success ] [, dataType ] )
    • url: The only mandatory parameter. This string contains the address to which to send the request. The returned data will be ignored if no other parameter is specified.
    • data: A plain object or string sent to the server with the request.
    • success: A callback function executed if the request succeeds. It takes as an argument the returned data. It is also passed the text status of the response.
    • dataType: The type of data expected from the server. The default is Intelligent Guess (xml, json, script, text, html). If this parameter is provided, the success callback also must be provided.

    Examples

    Request resource.json from the server, send additional data, and ignore the returned result:

    $.get('//example.com/resource.json', {category:'client', type:'premium'});

    Request resource.json from the server, send additional data, and handle the returned response (json format):

    $.get('//example.com/resource.json', {category:'client', type:'premium'}, function(response) { alert("success"); $("#mypar").html(response.amount); });

    However, $.get doesn't provide any way to handle error.

    The above example (with error handling) can also be written as:

    $.get('//example.com/resource.json', {category:'client', type:'premium'}) .done(function(response) { alert("success"); $("#mypar").html(response.amount); }) .fail(function(error) { alert("error"); $("#mypar").html(error.statusText); });

    Ajax GET Equivalent

    $.get( url [, data ] [, success ] [, dataType ] ) is a shorthand Ajax function, equivalent to:

    $.ajax({ url: url, data: data, success: success, dataType: dataType });

    Ajax Post Method

    Sends an asynchronous http POST request to load data from the server. Its general form is:

    jQuery.post( url [, data ] [, success ] [, dataType ] )
    • url : This is the only mandatory parameter. This string contains the adress to which to send the request. The returned data will be ignored if no other parameter is specified
    • data : A plain object or string that is sent to the server with the request.
    • success : A callback function that is executed if the request succeeds. It takes as an argument the returned data. It is also passed the text status of the response.
    • dataType : The type of data expected from the server. The default is Intelligent Guess (xml, json, script, text, html). if this parameter is provided, then the success callback must be provided as well.

    Examples

    $.post('//example.com/form.php', {category:'client', type:'premium'});

    requests form.php from the server, sending additional data and ignoring the returned result

    $.post('//example.com/form.php', {category:'client', type:'premium'}, function(response){ alert("success"); $("#mypar").html(response.amount); });

    requests form.php from the server, sending additional data and handling the returned response (json format). This example can be written in this format:

    $.post('//example.com/form.php', {category:'client', type:'premium'}).done(function(response){ alert("success"); $("#mypar").html(response.amount); });

    The following example posts a form using Ajax and put results in a div

        jQuery.post demo // Attach a submit handler to the form $( "#searchForm" ).submit(function( event ) { // Stop form from submitting normally event.preventDefault(); // Get some values from elements on the page: var $form = $( this ), term = $form.find( "input[name='s']" ).val(), url = $form.attr( "action" ); // Send the data using post var posting = $.post( url, { s: term } ); // Put the results in a div posting.done(function( data ) { var content = $( data ).find( "#content" ); $( "#result" ).empty().append( content ); }); });   

    The following example use the github api to fetch the list of repositories of a user using jQuery.ajax() and put results in a div

        jQuery Get demo // Attach a submit handler to the form $( "#userForm" ).submit(function( event ) { // Stop form from submitting normally event.preventDefault(); // Get some values from elements on the page: var $form = $( this ), username = $form.find( "input[name='username']" ).val(), url = "//api.github.com/users/"+username+"/repos"; // Send the data using post var posting = $.post( url, { s: term } ); //Ajax Function to send a get request $.ajax({ type: "GET", url: url, dataType:"jsonp" success: function(response){ //if request if made successfully then the response represent the data $( "#result" ).empty().append( response ); } }); });   

    Ajax POST Equivalent

    $.post( url [, data ] [, success ] [, dataType ] ) is a shorthand Ajax function, equivalent to:

    $.ajax({ type: "POST", url: url, data: data, success: success, dataType: dataType });