JQuery cheatsheet
JQuery
Used for:
- Manipulate HTML/DOM and CSS.
- event methods HTML
- Animations and effects
- AJAX
Basic syntax:
1 | // don't use Jquery until the page is loaded |
$
access to jQuery.(selector)
gets HTML elementaction()
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 | // animation: silde up and down |
Working with the DOM
No parameters = “gets”. With parameters = “sets”
text()
: no format, text.html()
: with format, HTMLval()
: value fieldatr('atrib', 'new value')
: set, similar toval('')
1 | $(document).ready(function(){ |
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()`, optionalget
1
$.get(url, callback);
post
1
$.post(url, data, callback);