JQuery cheatsheet

JQuery

Used for:

  • Manipulate HTML/DOM and CSS.
  • event methods HTML
  • Animations and effects
  • AJAX

Basic syntax:

1
2
3
4
5
6
7
8
9
// don't use Jquery until the page is loaded
$(document).ready(function(){
// jQuery
$(selector).action();
});
$(function(){
// more jQuery after load
$(selector).action();
});
  • $ access to jQuery.
  • (selector) gets HTML element
  • action() does operation on element

Selectors

  • by name, id, class, type, attributes, value…
    1
    2
    3
    4
    5
    6
    7
    $(document).ready(function(){
    // when click on button
    $(' button').click(function(){
    // hide paragraph
    $('p' ).hide();
    });
    });
  • $("#button") -> id="button" -> ids should be unique
  • $(".button") -> class="button" -> may return many

Callbacks on Jquery

  • With callback
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    $(document).ready(function(){
    $('button').click(function(){
    $('p').hide('slow', function() {
    // once hidden, show alert
    alert('The paragraph is now hidden');
    });
    });
    });
    //executed first
    alert("The paragraph is not hidden");
  • Without callback
    1
    2
    3
    4
    5
    $('button').click(function(){
    $('p').hide(1000);
    // it will not wait for the paragraphs to be hidden
    alert('The paragraph is now hidden');
    });

Chaining

1
2
3
4
// animation: silde up and down
$('#p1').css('color', 'red')
.slideUp(2000)
.slideDown(2000);

Working with the DOM

No parameters = “gets”. With parameters = “sets”

  • text(): no format, text.
  • html(): with format, HTML
  • val(): value field
  • atr('atrib', 'new value'): set, similar to val('')
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$(document).ready(function(){
$('#btn1').click(function(){
$('.test1').text(function(i, origText){
return 'Old text: ' + origText
+ ' New text: Hello world! (index: ' + i + ')';
});
});

$('#btn2').click(function(){
$('.test2').html(function(i, origText){
return 'Old html: ' + origText
+ ' New html: Hello <b>world!</b> (index: ' + i + ')';
});
});
});

AJAX

  • allow asynchronous communication bertween server and browser in XML via JS

  • loads data in background and deploys them without a full web reload

  • jQuery uses HTTP GET y POST to obtain text, HTML, XML or JSON de un servidor remoto

  • 3 functions with similar parameters:

    • load

      1
      2
      3
      4
      $(selector).load(url, data, callback);
      // url: mandatory
      // data: <key,value> pairs for the request, optional
      // callback: whet should it do after `load()`, optional
    • get

      1
      $.get(url, callback);
    • post

      1
      $.post(url, data, callback);