1. Using jQuery
- Where to get jQuery libraries
- Including jQuery in your page
- $
- Executing client code after page loads
- How can jQuery() be called
2. Working with DOM elements
- Updating DOM elements
- Styling elements
- Elements geometry
- Manipulating elements
- Setting visibility of elements
3. Selectors
4. Language features
- Chaining
- For each
- Event handlers
5. Attaching data to elements
- is()
6. Avoiding $ conflicts
7. Parsing XML
8. Effects
- Fade/slide
9. AJAX
- Load script
- Making AJAX calls
- GET with AJAX
- GET JSON with AJAX
- AJAX with selector
- Updating data
10. Datatables
- Static tables
- Dynamic tables
- Select Row
- Reload datatable data
11. Kendo UI
- Using Kendo
- Grid with static data
- Using Grid with dynamic data
- Handle selected row in Kendo Grid
jQuery is a set of JavaScript libraries that make it easier to write client side code. More details on jquery.com
It abstracts browers differences.
- Simplifies DOM navigation
- CSS manipulation
- DOM event handling
- Effect and animations
- Simplified AJAX
- Extensibility through plugins
jQuery examples on W3schools.com
1. Using jQuery
Where to get jQuery libraries
You can refer your code to libraries a CDN (Content Delivery Network) provided by
Microsoft (http://ajax.microsoft.com/ajax/jQuery/jQuery-x.x.x.min.js)
Google (http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js)
jQuery (http://code.jQuery.com/jquery-x.x.x.min.js)
Advantage of using jQuery from CDN is caching, if your website is deployed to many (100) servers, because if you refer to script in your website, browser will cache each one of many (100) servers that will be reached.
jQuery.min.js - removed comments, shorten variables for execution
version 1 -supports IE6+
version 2 -supports IE9+
Including jQuery in your page
JavaScript // include locally <script src="scripts/jquery.min.js"></script> // refer to Microsoft CDN <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"></script>
$
$("div") is the same as jQuery("div")
Executing client code after page loads
Code example:Ready function
Document ready function gets called when browser completes loading the page into DOM.
This is jQuery variant of handling window.loaded event. window.onload gets called before images get loaded.
If multiple ready functions are defined they get executed in sequence order as they were defined.
JavaScript <script> // jQuery(document).ready( function() { // old syntax (without alias) // $(document).ready( function() { // old syntax $(function() { // do something }); </script>
How can jQuery() be called
JavaScript $("table tr:odd").css("color", "blue"); // selector $(this).css("color", "blue"); // DOM element $("<a src="mypage.html>link</a>").appendto("body); // HTML string $(function() // callback { // do something here } );
2. Working with DOM elements
Updating DOM elements
Code example:Update DOM
An html element marked with id tag
HTML <div id="myId">Some text</div>can be manipulated like below
JavaScript $("#myId").text("my text");
$("#myId").append("my text");
$("#myId").html("my text"); // inner html
$("#myId").val("my text"); // e.g. selected value from a list - always string
$("#myId").attr("alt", "banner");
$("#myId").removeAttr("alt");
Styling elements
JavaScript .css("color", "blue") .hasClass("myClassName") .addClass("myClassName yourClassName") .toggleClass("newClassName") // replace class .removeClass("myClassName")
Elements geometry
JavaScript $(window).width(); $("#myid").position().left; // relative to document $("#myid").offset().left; // relative to parent
Manipulating elements
JavaScript $("#myid").insertAfter("<br/>"); // after() works the same $("#myid").replaceWith(" an html text "); $("#myid").remove(); // removes itself $("#myDropDown").append("row 1")
Setting visibility of elements
JavaScript $("#myId").show(); $("#myId").hide(); $("#myId").attr("disabled", true);
3. Selectors
JavaScript $(" .myclass") // all elements that are assigned to .myclass - be aware of space before .
4. Language features
Chaining
Chaining works because jQuery returns reference to the same jQuery object
JavaScript $(table tr:odd).css("color", "blue").height(20);
For each
JavaScript $("table tr").each( function(index, value) { $(this).css(...) } );
Event handlers
JavaScript $(document).ready( function() { $("#button").click( function() { // do something when user clicks the button }); });
5. Attaching data to elements
JavaScript $("#myid").data("key", "value"); var $("#myid").data("key");
is()
JavaScript if $("#myCheckBox").is(":checked") {... }
6. Avoiding $ conflicts
JavaScript jQuery.noConflict(); // disassociate jQuery alias $.
jQuery().each(....) // use jQuery() then
jQuery( function($) { // you can use $ here as } );
7. Parsing XML
Code example:ParseXml
JavaScript var xmlText = "<people><person><firstName>John</firstName></person></people>"; var xmlDoc = $.parseXML( xmlText ); var $xml = $( xmlDoc ); var $firstName = $xml.find( "firstName" ); $( "#label" ).append( $firstName.text() );
8. Effects
Fade/slide
Code example:Effects
JavaScript $("#laleb1").slideUp().slideDown(); $("#label2").fadeOut().fadeIn();
9. AJAX
AJAX call can be written in pure JavaScript , but it requires more code and handling for different browsers types.
Code example:AJAX
(requires http://localhost/asp.asp and asp_post.asp)
Load script
JavaScript $.getScript("mycode.js"); // load code when it is needed
Making AJAX calls
.ajax() is generic function that can be used to make htpp call (both get and post). It provides more configuration options like caching.
JavaScript $.ajax({ url: "http://localhost/asp.asp", context: document.body }).done( function(data, status) { $("#lblAjax").append("Data: " + data + " Status: " + status); });
GET with AJAX
get() Executes http GET call
JavaScript $.get( "http://localhost/asp.asp", function(data, status){ $("#lblGet").append("Data: " + data + " Status: " + status); } );
GET JSON with AJAX
getJSON() returns JavaScript objects that may represent business data
JavaScript $.getJSON("http://localhost/personData.html", function(data){ // data is JavaScript object alert(data.msg); } );
AJAX with selector
load() allows to make a GET AJAX call and assign either TEXT or HTML to a DOM element
JavaScript $("#lblLoad").load("http://localhost/asp.asp");
Updating data
post() allows to post data to the web server
JavaScript $.post( "http://localhost/asp_post.asp", { id:"1", name:"John" }, function(data, status){ $("#lblPost").append("Data: " + data + " Status: " + status); } );
10. Datatables
Static tables
Code example:Datatable with predefined content
HTML <script src="scripts/jquery-1.6.2.min.js"></script> <script src="scripts/jquery.dataTables.js"></script> <script> $(document).ready(function(){ $('#people').dataTable(); }); </script> </head> <body> <table id="people"> <thead> <tr> <th>Id</th> <th>Name</th> <th>Department</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>John</td> <td>IT</td> </tr> ... </tbody> </table>
Dynamic tables
Code example:Table with dynamic column definition
HTML <script src="scripts/jquery-1.6.2.min.js"></script> <script src="scripts/jquery.dataTables.js"></script> <script> $(document).ready(function() { /* content of http://localhost/peopleJSON.txt { "aaData": [ [ "1-", "John", "IT" ], [ "2", "Paul", "FI" ], [ "3", "<a href='george.txt'>George</a>", "IT" ] ], "aoColumns": [ { "sTitle": "ID-" }, { "sTitle": "Name" }, { "sTitle": "Department" } ] } */ $.get( "http://localhost/peopleJSON.txt", function (data, status) { $("#output").text(data); $('#people').dataTable( JSON.parse(data) ); } ); } ); </script> ... <table id="people"></table>
Select Row
Code example:Table supporting row selection
HTML $(document).ready(function() { $('#people').dataTable(); // $("#people tbody tr").click( function( e ) { ! does NOT work with dynamically created rows $("#people").on( 'click', 'tr', function( e ) { if (this.firstChild.nodeName != 'TH') { if ( $(this).hasClass('row_selected') ) { $(this).removeClass('row_selected'); // unselect } else { $('tr.row_selected').removeClass('row_selected'); $(this).addClass('row_selected'); // get selected cell text var td = this.children[1]; alert(td.innerText + " has been selected"); } } }); } );
Reload datatable data
HTML $('#tableDiv').empty(); $('#tableDiv').append("<table id=\"myDataTable\"></table>");
11. Kendo UI
Kendo UI or jQuery UI
Using Kendo
HTML <link href="styles/kendo.common.min.css" rel="stylesheet" /> <link href="styles/kendo.default.min.css" rel="stylesheet" /> <script src="js/jquery.min.js"></script> <script src="js/kendo.web.min.js"></script> <input id="datepicker" onchange="alert(this.value)" />
JavaScript $(function() { $("#datepicker").kendoDatePicker(); });
Grid with static data
Grid can used with static data defined in <table> element
HTML <table id="grid"> <thead> <tr> <th data-field="firstName">First Name</th> <th data-field="lastName">Last Name</th> <th data-field="department">Department</th> </tr> </thead> <tbody> <tr> <td>John</td> <td>First</td> <td>IT</td> </tr> </tbody> </table>
JavaScript $("#grid").kendoGrid({ groupable: true, scrollable: true, sortable: true, pageable: true, selectable: "row" });
Using Grid with dynamic data
HTML <div id="grid"></div>
JavaScript var columns =[ { field: "firstName" }, { field: "lastName" }, { field: "department" } ]; var people = [ { firstName: "John", lastName: "First", department: "IT" }, { firstName: "Paul", lastName: "Second", department: "Finance" }, ]; $("#grid").kendoGrid({ columns: columns, dataSource: people });
Handle selected row in Kendo Grid
JavaScript $("#grid").kendoGrid({ selectable: true });and then you can get selected row as an object with columns as members
JavaScript function buttonOnClick() { var grid = $("#grid").data("kendoGrid"); var selectedItem = grid.dataItem(grid.select()); if (selectedItem != null) alert(selectedItem.firstName); else alert("No row has been selected") }