Introduction:
This post is to provide some quick refreshing facts and best practices for those folks who haven't worked on jQuery for a while. For beginners, it's better to go through the basic/advance tutorials first and check back with this later.
About jQuery:
1. jQuery is a JavaScript Library
2. jQuery greatly simplifies JavaScript programming
jQuery concepts:
This post is to provide some quick refreshing facts and best practices for those folks who haven't worked on jQuery for a while. For beginners, it's better to go through the basic/advance tutorials first and check back with this later.
About jQuery:
1. jQuery is a JavaScript Library
2. jQuery greatly simplifies JavaScript programming
jQuery concepts:
- Pointing to jQuery
- From local reference - ''- assuming jquery.js file is in same folder with the html
- Content Delivery Network (CDN) based - 'src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"'
- launching code - Option-02 is prepared as that's invoked as soon as the DOM is ready rather waiting the page loaded fully (including images)
- Option-01: window.onload = function() { //code};
- Option-02: $( document ).ready(function() { //code });
- Option-03: is shortcut to option-02. '$(function(){ //code});'
- Callbacks and functions - A callback is a function that is passed as argument to another function and will be executed only after the function where it's passed has completed
- Callback without Arguments - '$.get('aPage.html', callBackFn);'
- Callback with Arguments -
- Not possible - '$.get('aPage.html', callBackFn(param1, param2));'. This will execute the callBackFn first and return of it will be passed to get function
- Correct way - '$.get( "aPage.html", function() { callBackFn( param1, param2 ); });'
- $ vs $()
- Methods called on jQuery selections (used $()) are in the $.fn namespace, and automatically receive and return the selection as this
- Methods in the $ namespace are generally utility-type methods, and do not work with selections; they are not automatically passed any arguments
- Ways to avoid conflict with other libraries
- new alias - noConflict returns a reference to jQuery function
'var $j = jQuery.noConflict();' - use self invoking function -
'jQuery.noConflict();(function($){ //code})(jQuery);' - Argument through jQuery(document).ready() function
'jQuery(document).ready(function( $ ) { // code });'
- Selecting elements
- by
- tag name - '$("aDOM");'
- ID - '$("#idToFind");'
- class name - '$(".className");'
- Pseudo selectors - :visible :enabled :checked :text :button :file (see references for complete list)
- comma to use to select multiple DOM objects
- chaining - any method call on a selection returning a jQuery object, allows to call jQuery method on the object without pausing for a semicolon.
'("#aDiv").find("p").eq("1").html("Changed text");' - find second p in a dive called aDiv and change content
- Methods -
- getter/setter - html, text, val - can be both setter (with argument) or getter (no argument)
- Move, copy and remove elements
- Attributes - .attr() to get/set value to selector's attribute.
- Object of key-value pair can be passed to set multiple
- Selection traversing
- parents - .parent() .parents() .parentUntil() .closest().
- children - .children() .find().
- Siblings - .prev() .next() .siblings() .nextAll() .prevAll() .nextUnti() .prevUntil()
- Styling and dimensions
- CSS classes - addClass("aClass") removeClass("aClass").
- Dimensions - width, height - getter/setter
- Data methods - stores data to the element and manages the memory issues.
'$("#aDiv").data("aKey", {name:"Riaz"});' '$("#aDiv").data("aKey");'
- Utility methods -
- $.trim() -
- $.each() - generic iterator function for looping over object/arrays/ array-like objects
example:
'$.each([1,2,3,4], function(idx, val){ console.log("Element "+idx + " is "+val);});'
output:
Element 0 is 1
Element 1 is 2
Element 2 is 3
Element 3 is 4
- $.proxy(function, scopeObj) -
example:
var aFn = function() { console.log( this ); };
var aObj = { name: "Riaz" };
aFn();
var proxyAFn = $.proxy( aFn, aObj );
myProxyFunction();
Output:
Window {external: Object, chrome: Object, document: document, speechSynthesis: SpeechSynthesis, caches: CacheStorage…}
Object {name: "Riaz"}
- $.type() - returns the type of passed object
- .map() - returns array from matched elements from selector
- jQuery events -
- Some common events
- Event call syntax -
- Assign an event - $("p").click();
- Indicates what should happen after event -
$("p").click(function(){ /*actions*/}); - Usage of '.on()'.
- All the methods above are shortcut of this
- Syntax - '$("p").on("click", function(){/*actions*/});'
- Handling event -
- Many events single event handler - comma separated events
- Multiple event and event handler association -'$( "p" ).on({ "click": function() { console.log( "clicked!" ); },
"mouseover": function() { console.log( "hovered!" ); } });' - Data can be passed to event -
'.on( "click", {name:"Riaz"}, function(event){ console.log("Name:"+event.data.name");});'
Mouse Event | Key Event | Form Event | window Event |
---|---|---|---|
click | keypress | submit | load |
dblclick | keydown | change | unload |
mouseenter | keyup | focus | size |
mouseleave | blur | scroll |
- Instead of anonymous function, a named function can be passed as event handler
- Namespacing event - for complex and plugin application, it's a good idea to namespace application specific events to avoid conflict
- tead down events
- Unbind all click event - $( "p" ).off( "click" );
- Unbind only aHandler from click - $( "p" ).off( "click", aHandler );
- Event handler to run only once - using '.one(...)'
- Properties and method of eventhanlder
- Properties - pageX pageY which type data target namespace timestamp etc.
- Methods - preventDefault() stopPropagation() etc
12. Ajax in jQuery
- Syntax - '$.ajax(...)'
- Data types - type of data you expect to get back from an Ajax request
- text html script json jsonp xml
- API -
// Using the core $.ajax() method
$.ajax({
// The URL for the request
url: "- page url",
// The data to send (will be converted to a query string)
data: { },
// Whether this is a POST or GET request
type: "GET",
// The type of data we expect back
dataType : "json",
// Code to run if the request succeeds;
success: function( json ) { /* do something */ },
// Code to run if fails; raw request and status codes are passed
error: function( xhr, status, errorThrown ) { /* do something */ },
// Code to run regardless of success or failure
complete: function( xhr, status ) { /* do something */ } }); - Convenient functions - below functions are wrapper around core .ajax()
- functions - $.get $.post $.getScript $.getJSON
- parameters -
- Required - url
- Optional - data success dataType
- Ajax events
- Local events - specify within ajax request object
- beforeSend success error complete
- Global events
- ajaxtStart ajaxStop
- Using $("#aForm").serialize() - serializes form data into a query string
- Using $("#aForm").serializeArray() - serializes to array of objects
Resources:
1. http://api.jquery.com/
2. http://www.w3schools.com/jquery/
3. https://learn.jquery.com/
No comments:
Post a Comment