Your SlideShare is downloading. ×
JQuery Basics
JQuery Basics
JQuery Basics
JQuery Basics
JQuery Basics
JQuery Basics
JQuery Basics
JQuery Basics
JQuery Basics
JQuery Basics
JQuery Basics
JQuery Basics
JQuery Basics
JQuery Basics
JQuery Basics
JQuery Basics
JQuery Basics
JQuery Basics
JQuery Basics
JQuery Basics
JQuery Basics
JQuery Basics
JQuery Basics
Upcoming SlideShare
Loading in...5

Thanks for flagging this SlideShare!

Oops! An error has occurred.

Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

JQuery Basics


Published on

Short presentation about JQuery

Short presentation about JQuery

Published in: Technology
  • Be the first to comment

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

No notes for slide


  • 1. Learning JQuery
  • 2. Why JQuery?
      • Cross-Browser Compatibility
      • CSS Selectors
      • Chaining
  • 3. Start using JQuery
    • //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 });
    • //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 });
  • 4. ID Selectors:
    • $(document).ready(function(){
    •      //get the element with id &quot;selected&quot;
    •     $('#selected').addClass('whatever');
    •      //li childs of element with &quot;selected&quot; 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'); 
    • });
  • 5. 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 &quot;mailto&quot; string (regulat exp)
    • $('a[@href^=&quot;mailto:&quot;]').addClass('mailto');
    • //attribute ending with string (reg exp)
    • $('a[@href$=&quot;mailto:&quot;]').addClass('mailto');
    • //attribute containing string (reg exp)
    • $('a[@href*=&quot;mysite&quot;]').addClass('my-site');
  • 6. Custom Selectors:
    • //get the second div elemet with &quot;class-name&quot; 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(&quot;wanted-string&quot;)').addClass('css-class');
  • 7. More custom selectors
    • :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
    • :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;) )
  • 8. 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 &quot;Gigi&quot; string $('td:contains(&quot;Gigi&quot;)').next().addClass('next-class');
    • //add hightlight class to all siblings of td element $('td:contains(&quot;Gigi&quot;)').siblings().addClass('highlight'); 
  • 9. Event handling
    • $('#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'); });
  • 10. 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();
  • 11. Inline CSS Modification
    • <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); });
  • 12. 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=&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();
  • 13. Chaining and queueing events
    • //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'); });
  • 14. 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(&quot;<li> &quot; + $(this).find('title').text() + &quot;</li>&quot;);     }); });
  • 15. JavaScript Notation Object (JSON)
    • //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);
  • 16. JSON support in JQuery
    • //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     }); });
  • 17. AJAX
    • //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);          }); });
  • 18. 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){ } });
  • 19. 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(&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;);     }); });
  • 20. XML parsing example
    • //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 $(
  • 21. 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     }); });
  • 22. Links
  • 23.