Date post: | 19-Jan-2015 |
Category: |
Technology |
Upload: | alin-taranu |
View: | 9,475 times |
Download: | 0 times |
Learning JQuery
Why JQuery?
1.Cross-Browser Compatibility2.CSS Selectors3.Chaining
Start using JQuery//include jquery lib <script type="text/javascript" src="jquery.js" />
//usually used version$(document).ready(function() { // do this stuff when the HTML is all ready});//similar as previous definition$(function() {//run this when the HTML is done downloading});
$(window).load(function() {//run this when the whole page has been downloaded //including pictures});
ID Selectors: $(document).ready(function(){ //get the element with id "selected" $('#selected').addClass('whatever'); //li childs of element with "selected" id $('#selected > li').addClass('horizontal'); //negation of pseudo-class; //all sub level items that don't have horizontal class; $('#selected li:not('.horizontal')').addClass('sub-level'); });
XPath Selectors:
$('a[@title]'); //a elements that have title attribute$('div[ol]'); //div elements that contains ol element
//add mailto class to elements that have //the title attribute starting with "mailto" string (regulat exp) $('a[@href^="mailto:"]').addClass('mailto');
//attribute ending with string (reg exp)$('a[@href$="mailto:"]').addClass('mailto');
//attribute containing string (reg exp) $('a[@href*="mysite"]').addClass('my-site');
Custom Selectors:
//get the second div elemet with "class-name" css class (javascript is zero-based)$('div.class-name:eq(1)');
//get the first child of div's parent (css is one-based) $('div:nth-child(1)');
$('tr:odd').addClass('odd'); // add css class to odd rows$('tr:even').addClass('even'); // add css class to even rows
//javascript pseudo-selector$('td:contains("wanted-string")').addClass('css-class');
More custom selectors
:first, :last ( $("tr:first") ):header, :hidden, :visible ( $(":header").css ... ):input, :text, :radio, :submit, ... (var allInputs = $(":input");)
:eq(index), :gt(index), :lt(index) ( $("td:eq(2)") ):contains(text), :has(selector) ($("div:has(p)").addClass("test");):first-child, :last-child:not(selector) ( $("input:not(:checked) + span") )parent > child ( $("#main > *").css("border", "3px double red"); ):empty ( $("td:empty").text("Was empty!") )
Dom Traversing methods
//gets all tr then filter them using :odd JavaScript pseudo-selector$('tr').filter(':odd').addClass('odd-class');
//get th element's parent$('th').parent().addClass('table-heading');
//add css class to the next sibling of td element that contains "Gigi" string$('td:contains("Gigi")').next().addClass('next-class');
//add hightlight class to all siblings of td element$('td:contains("Gigi")').siblings().addClass('highlight');
Event handling$('#element-id').bind('click', function() { //bind click event to element identified by "element-id" id $('body').removeClass().addClass('new-cass'); });
#######################
var toggleSwitcher = function() { //do something}//unbind an event$("#switcher").unbind('click', ToggleSwitcher);
Shorthand Events
$('#element-id').click(function(){ $(this).addClass('selected'); });
Event bindings examples$('#element-id').toggle(function(){ $('#switcher').addClass('hide'); //function executed on first click}, function(){ $('#switcher').addClass('show'); //function execute on second click});
$('#element-id').hover(function(){ $(this).addClass('hover'); //kinda' clear isn't it :)}, function(){ $(this).removeClass('hover');});
Trigger an event
$('#switcher').trigger('click'); //obvious, huh? :)or//when no arguments, the behaviour is to trigger the event rather than bind it$('#switcher').click();
Inline CSS Modification<div id="books"> <div class="covers"> <a ...>$(document).ready(function() { var spacing = 140; $('#books').css({ //set styling to books container 'width': '160px', 'height': '300px', 'overflow': 'hidden' }).find('.covers a').css({ //get the a elements inside "#books .covers" 'float': 'none', 'position': 'absolute', 'left': 1000 }); var covers = $('#books .covers a'); covers.eq(0).css('left', 100); covers.eq(1).css('left', 100 + spacing); covers.eq(2).css('left', 100 + 2 * spacing);});
DOM manipulation//set the rel attribute to all a elements inside a div with chapter class (implicit loop) $('div.chapter a').attr({'rel' : 'external'});
$('div.chapter a').each(function(index) { $(this).attr({'rel' : 'external', 'id' : 'my-id-' + index}); });
//create a element and then insert it into page afterdiv element $('<a href="#top">back to top</a>').insertAfter('div.chapter p'); $('<a id="top"></a>').prependTo('body'); //insert element at the begining of body$('span.footnote').insertBefore('#footer'); //yup, before footer ;)
.wrap(); //insert new element around every matched element
.html(); //replace html code of every element matched
.text(); //get\/set matched elements text
.empty();
.remove();
Chaining and queueing events//you can call .end() method to return to the previous collection$("div").hide("slow", function(){ $(this) .addClass("done") .find("span") .addClass("done") .end() .show("slow", function(){ $(this).removeClass("done"); });});
Queueing events
$('#elem-id').slideDown('slow', function(){ //slideUp animation will occur when the slideDown animation is done $('#elem-id').slideUp('slow'); });
Looping in JQuery//jquery object iterator$(’selector’).each(function(index){ //only index parameter});//generic iterator ($.each() or jQuery.each() can be used )jQuery.each( [0,1,2,3,4], function(index, item){ //notice that we have 2 parameters in the callback function});//other looping example<rss> <item><title>Title1</title><text>Text1</text></item> <item><title>Title 2</title><text>Text 2</text></item></rss>$.get('feed.xml', function(data){ $(data).find('item').each(function(){ $('#result').append("<li> " + $(this).find('title').text() + "</li>"); });});
JavaScript Notation Object (JSON)//define a json objectvar myJSONObject = {"bindings": [{"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},{"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},{"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}]};
//get a value from a json objectmyJSONObject.bindings[0].method // "newURI"//convert a json text(string) into a json object (not recomended)var myObject = eval('(' + myJSONtext + ')');
//using JSON parser to convert text to JSON object//reviver represent the callback function that will be called for every key and valuevar myObject = JSON.parse(myJSONtext, reviver);
JSON support in JQuery//a.json file{ "key": "value", "key2": [ "term1", "term2", "term3" ]}//jquery support for json files$.getJSON('a.json', function(data){ //get the json file content and convert it to json object $.each(data, function(entryIndex, entry){ //gota get used with those crappy anonymous functions :P //entryIndex == array index //entry = array row });});
AJAX//load a file$(document).ready(function() { $('#my-id .button').click(function() { $('#another-id').load('a.html'); });});//GET request; type= "xml", "html", "script", "json", "jsonp", or "text"$.get(url, params, callback, type)//send to server "name" and "time"$.get("test.php", { name: "John", time: "2pm" }, function(data){ $('#my-id').html(data); });//POST request$('#letter a').click(function() { //send the link text as post variable $.post('test.php', {name : $(this).text()}, function(data){ $('#my-id').html(data); });});
Low level ajax request
$.ajax({ url: 'autocomplete.php', async: true, beforeSend: function(){}, type: 'POST', //GET dataFilter: function(data, type) {}, data: {'search-text', $('#some-field-id').val()}, dataType: 'json', //html, script, xml timeout: 1000, error: function(){ alert('Error loading XML document'); }, success: function(data){ }});
Global AJAX request observers//These observers are global and are called when any AJAX request is made//regardless what code initiates it$(document).ready(function() { //loading message $('#loading').ajaxStart(function(){ $(this).show(); }).ajaxStop(function(){ $(this.hide()) }); //messages $('msg').ajaxComplete(function(request, settings){ $(this).append("<li>Request Complete.</li>"); }).ajaxError(function(event, request, settings){ $(this).append("<li>Error ocured reguesting " + settings.url + "</li>"); }).ajaxSuccess(function(evt, request, settings){ $(this).append("<li>Successful Request!</li>"); }).ajaxSend(function(evt, request, settings){ $(this).append("<li>Starting request at " + settings.url + "</li>"); });});
XML parsing example//example on how to an xml file and parse it$(function() { $('#update-target a').click(function() { $.ajax({ type: "GET", url: "labels.xml", dataType: "xml", success: function(xml) { $(xml).find('label').each(function(){ var id_text = $(this).attr('id') var name_text = $(this).find('name').text() $('<li></li>') .html(name_text + ' (' + id_text + ')') .appendTo('#update-target ol'); }); //close each( } }); //close $.ajax( }); //close click(}); //close $(
Serialize form
//NOTICE: //in order to serialize work you should also set a name attribute to input fields$(document).ready(function() { $(#form-wraper-id form).submit(function() { $.get('test.php', find('input').serialize(), function(data){ $('#my-id').html(data); }); return false; //disable page reloading caused by submit });});
Links
http://docs.jquery.com/Main_Page
http://www.json.org/