3. jQuery
Open source Javascript framework
Crossbrowser client side scripting
Uses CSS syntax for selection
Most used Javascript library
$ - synonymous with the jQuery function
3
4. Loading jQuery
Locally : <script src="/js/jquery.js">
CDN :
ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js
ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js
BEST PRACTICE :
When scripts are downloading they block everything else in almost
all browsers. Load scripts at the bottom of the page so they don't
interrupt page content downloads.
4
5. Ready state
The DOM is "ready" when everything on the page has loaded.
Stylesheets
JavaScripts
Images
In order to make sure that jQuery can find all the elements, wrap the
jQuery code within in the document ready function.
$(document).ready(function(){ … });
$(function() { … });
5
6. Selecting elements
Selector Reference :
http://www.w3schools.com/jquery/jquery_ref_selectors.asp
Pseudo selectors (:) - :first, :button, :input, :checked
Filtering selectors – has, not, filter, eq
Testing Selectors :
http://www.w3schools.com/jquery/trysel.asp
CONVENTION :
When storing selections in a variable prefix ‘$’ to indicate that the variable
contains a jQuery object.
6
7. Getters and setters
GET :
var htmlContent = $(“selector”).html()
var textContent = $(“selector”).text()
SET :
$(“selector”).html(‘content’)
$(“selector”).text(‘content’)
Example :
https://jsfiddle.net/NivedhithaV/aw9q87b5/2/
For form elements val() is used
7
8. Iteration
$( 'li' ).each(function( index, elem ) {
// this: the current DOM element
// index: the current element's index in the selection
// elem: the current DOM element (same as this)
$( elem ).prepend( '<b>' + index + ': </b>' );
});
Example :
https://jsfiddle.net/NivedhithaV/2shq5x69/1/
8
14. Binding events
Events –
Click, dblclick, change, blur, focus
Mouse events
Keyboard events
Bind/unbind – connecting/disconnecting event handler
One – connecting events to run only once
On – attaching one or more events, will work for current and future
elements
Trigger – triggering an event after binding
14
15. Other functions
preventDefault – prevents the default action of the event
$( "a" ).click(function( event ) {
event.preventDefault();
...
});
stopPropogation – prevents event from bubbling up to parent
Example : https://jsfiddle.net/NivedhithaV/32rvk8zk/1/
15
19. Asynchronous javascript and XML
Loading data from server without page reload
Uses Xmlhttprequest - XHR
Returns jqXHR object — a jQuery XML HTTP Request
Form serialize
Example - https://jsfiddle.net/NivedhithaV/mhJRQ/9/
19