JQuery Basics


Published on

Short presentation about JQuery

Published in: Technology

JQuery Basics

  1. 1. Learning JQuery
  2. 2. Why JQuery? <ul><ul><li>Cross-Browser Compatibility </li></ul></ul><ul><ul><li>CSS Selectors </li></ul></ul><ul><ul><li>Chaining </li></ul></ul>
  3. 3. Start using JQuery <ul><li>//include jquery lib <script type=&quot;text/javascript&quot; src=&quot;jquery.js&quot; /> //usually used version $(document).ready(function() {      // do this stuff when the HTML is all ready }); </li></ul><ul><li>//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 }); </li></ul>
  4. 4. ID Selectors: <ul><li>  </li></ul><ul><li>$(document).ready(function(){ </li></ul><ul><li>      </li></ul><ul><li>     //get the element with id &quot;selected&quot; </li></ul><ul><li>    $('#selected').addClass('whatever'); </li></ul><ul><li>  </li></ul><ul><li>     //li childs of element with &quot;selected&quot; id     $('#selected > li').addClass('horizontal'); </li></ul><ul><li>      </li></ul><ul><li>     //negation of pseudo-class;  </li></ul><ul><li>    //all sub level items that don't have horizontal class;     $('#selected li:not('.horizontal')').addClass('sub-level');  </li></ul><ul><li>  </li></ul><ul><li>}); </li></ul>
  5. 5. XPath Selectors: <ul><li>$('a[@title]'); //a elements that have title attribute $('div[ol]'); //div elements that contains ol element </li></ul><ul><li>//add mailto class to elements that have   </li></ul><ul><li>//the title attribute starting with &quot;mailto&quot; string (regulat exp) </li></ul><ul><li>$('a[@href^=&quot;mailto:&quot;]').addClass('mailto'); </li></ul><ul><li>//attribute ending with string (reg exp) </li></ul><ul><li>$('a[@href$=&quot;mailto:&quot;]').addClass('mailto'); </li></ul><ul><li>//attribute containing string (reg exp) </li></ul><ul><li>$('a[@href*=&quot;mysite&quot;]').addClass('my-site'); </li></ul>
  6. 6. Custom Selectors: <ul><li>//get the second div elemet with &quot;class-name&quot; css class (javascript is zero-based) </li></ul><ul><li>$('div.class-name:eq(1)'); </li></ul><ul><li>//get the first child of div's parent (css is one-based) </li></ul><ul><li>$('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(&quot;wanted-string&quot;)').addClass('css-class'); </li></ul>
  7. 7. More custom selectors <ul><li>:first, :last ( $(&quot;tr: first &quot;) ) :header, :hidden, :visible ( $(&quot;: header &quot;).css ... ) :input, :text, :radio, :submit, ... (var allInputs = $(&quot;: input &quot;);) :eq(index), :gt(index), :lt(index) ( $(&quot;td: eq (2)&quot;) ) :contains(text), :has(selector) ( $(&quot;div: has (p)&quot;).addClass(&quot;test&quot;); ) :first-child, :last-child </li></ul><ul><li>:not(selector) ( $(&quot;input: not (: checked ) + span&quot;) ) parent > child ( $(&quot;#main > *&quot;).css(&quot;border&quot;, &quot;3px double red&quot;); ) :empty ( $(&quot;td: empty &quot;).text(&quot;Was empty!&quot;) ) </li></ul>
  8. 8. Dom Traversing methods <ul><li>//gets all tr then filter them using :odd JavaScript pseudo-selector $('tr').filter(':odd').addClass('odd-class'); </li></ul><ul><li>//get th element's parent $('th').parent().addClass('table-heading'); </li></ul><ul><li>//add css class to the next sibling of td element that contains &quot;Gigi&quot; string $('td:contains(&quot;Gigi&quot;)').next().addClass('next-class'); </li></ul><ul><li>//add hightlight class to all siblings of td element $('td:contains(&quot;Gigi&quot;)').siblings().addClass('highlight');  </li></ul>
  9. 9. Event handling <ul><li>$('#element-id').bind('click', function() {     //bind click event to element identified by &quot;element-id&quot; id     $('body').removeClass().addClass('new-cass'); }); ####################### var toggleSwitcher = function() {     //do something } //unbind an event $(&quot;#switcher&quot;).unbind('click', ToggleSwitcher); Shorthand Events $('#element-id').click(function(){     $(this).addClass('selected'); }); </li></ul>
  10. 10. Event bindings examples <ul><li>$('#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 </li></ul><ul><li>//when no arguments, the behaviour is to trigger the event rather than bind it $('#switcher').click(); </li></ul>
  11. 11. Inline CSS Modification <ul><li><div id=&quot;books&quot;>     <div class=&quot;covers&quot;>         <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 &quot;#books .covers&quot;         '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); }); </li></ul>
  12. 12. DOM manipulation <ul><li>//set the rel attribute to all a elements inside a div with chapter class (implicit loop) </li></ul><ul><li>$('div.chapter a').attr({'rel' : 'external'}); </li></ul><ul><li>$('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=&quot;#top&quot;>back to top</a>').insertAfter('div.chapter p'); $('<a id=&quot;top&quot;></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(); </li></ul>
  13. 13. Chaining and queueing events <ul><li>//you can call .end() method to return to the previous collection $(&quot;div&quot;).hide(&quot;slow&quot;, function(){   $(this)     .addClass(&quot;done&quot;)     .find(&quot;span&quot;)     .addClass(&quot;done&quot;)     .end()     .show(&quot;slow&quot;, function(){       $(this).removeClass(&quot;done&quot;);     }); }); Queueing events $('#elem-id').slideDown('slow', function(){     //slideUp animation will occur when the slideDown animation is done     $('#elem-id').slideUp('slow'); }); </li></ul>
  14. 14. Looping in JQuery <ul><li>//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(&quot;<li> &quot; + $(this).find('title').text() + &quot;</li>&quot;);     }); }); </li></ul>
  15. 15. JavaScript Notation Object (JSON) <ul><li>//define a json object var myJSONObject = {&quot;bindings&quot;: [ {&quot;ircEvent&quot;: &quot;PRIVMSG&quot;, &quot;method&quot;: &quot;newURI&quot;, &quot;regex&quot;: &quot;^http://.*&quot;}, {&quot;ircEvent&quot;: &quot;PRIVMSG&quot;, &quot;method&quot;: &quot;deleteURI&quot;, &quot;regex&quot;: &quot;^delete.*&quot;}, {&quot;ircEvent&quot;: &quot;PRIVMSG&quot;, &quot;method&quot;: &quot;randomURI&quot;, &quot;regex&quot;: &quot;^random.*&quot;} ] }; //get a value from a json object myJSONObject.bindings[0].method // &quot;newURI&quot; //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 value var myObject = JSON.parse(myJSONtext, reviver); </li></ul>
  16. 16. JSON support in JQuery <ul><li>//a.json file {     &quot;key&quot;: &quot;value&quot;,     &quot;key2&quot;: [         &quot;term1&quot;,         &quot;term2&quot;,         &quot;term3&quot;     ] } //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     }); }); </li></ul>
  17. 17. AJAX <ul><li>//load a file $(document).ready(function() {     $('#my-id .button').click(function() {         $('#another-id').load('a.html');     }); }); //GET request; type= &quot;xml&quot;, &quot;html&quot;, &quot;script&quot;, &quot;json&quot;, &quot;jsonp&quot;, or &quot;text&quot; $.get(url, params, callback, type) //send to server &quot;name&quot; and &quot;time&quot; $.get(&quot;test.php&quot;, { name: &quot;John&quot;, time: &quot;2pm&quot; }, 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);          }); }); </li></ul>
  18. 18. Low level ajax request <ul><li>  $.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){ } }); </li></ul>
  19. 19. Global AJAX request observers <ul><li>//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(&quot;<li>Request Complete.</li>&quot;);     }).ajaxError(function(event, request, settings){         $(this).append(&quot;<li>Error ocured reguesting &quot; + settings.url + &quot;</li>&quot;);     }).ajaxSuccess(function(evt, request, settings){         $(this).append(&quot;<li>Successful Request!</li>&quot;);     }).ajaxSend(function(evt, request, settings){         $(this).append(&quot;<li>Starting request at &quot; + settings.url + &quot;</li>&quot;);     }); }); </li></ul>
  20. 20. XML parsing example <ul><li>//example on how to an xml file and parse it $(function() {   $('#update-target a').click(function() {     $.ajax({       type: &quot;GET&quot;,       url: &quot;labels.xml&quot;,       dataType: &quot;xml&quot;,       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 $( </li></ul>
  21. 21. Serialize form <ul><li>//NOTICE:  </li></ul><ul><li>//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     }); }); </li></ul>
  22. 22. Links <ul><li>http://docs.jquery.com/Main_Page </li></ul><ul><li>http://www.json.org/ </li></ul>