jQuery Notes

These days Apps are the need of time, most of the server side application is targetting to transform into client side Apps, so need of jQuery is equally getting important on these days.

Let us understand what, why, how jQuery is useful and important for us.

What is jQuery?

jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript.

Why is jQuery?

avaScript and jQuery usage are always up for discussion. Let’s start with basics of of the two and why jQuery might be a better option.

JavaScript is a raw programming language which has been used for a long time by professional IT programmers. It allows the client-side to interact with the user, alter the document content, communicate asynchronously etc. It uses syntax, and programming skills are needed. Thus, one needs to be professional to use it.

jQuery is a Javascript library designed to ease the client-side scripting of HTML. It is fast, concise and very flexible. There are so many libraries available, that we usuallly don’t need to write query for it… unlike Javascript. There are various plugins available for jQuery too, but these are some of the more broad reasons to choose jQuery.

For modern web developers, jQuery is a blessing.  Let’s discuss some of these advantages:

  1. Open Source – jQuery is developed by and available in the Open source community, thus it is free to use (like most programming languages)
  2. Endless Tutorial – There are a ton of tutorials to help any novice developer to design a web page. These tutorials will help you step-by-step to use each plugin or a tool.
  3. Huge Library – From simple items like border radius, image slider, design forms, to placing grids, and display audio/videos… the resources are endless. These plugins are so simple to use that you can can plug and play the code in just a few minutes.
  4. Cross-platform – jQuery is great at handling all cross-browser issues. Some Javascript’s have problems in early versions of IE and Firefox. But, jQuery has helped eliminate this issue. This avoids having to write different codes for different browsers. It results in high efficiency and less hassles.
  5. SEO -jQuery effects are like Flash and can’t really be utilized for SEO. The larger benefit of jQuery is that the files are very small and can be easily optimized for site speed. This is especially beneficial for mobile-friendly sites too. There are plugins to display images and audio-video files easily on a page instead of embedding them directly.
How to use jQuery effectively?

Downloading jQuery
– Download jQuery Files from jQuery Site (Development)
– NuGet Package Manager
– Install-Package jQuery
– Node Package Manager
– npm install jQuery
– Content Delivery Network (CDN) (Production)
https://cdnjs.com/libraries
http://code.jquery.com/jquery-2.1.4.min.js
https://developers.google.com/speed/libraries/
http://www.asp.net/ajax/cdn
2. IDE
– Visual Studio 2010+
– Visual Studio Code (VSCode)
– SublimeText
– ATOM
– Bracket
– Eclipse JavaScript IDE

What are JavaScript Object definition Syntaxes are available for Coding?
– var obj = {};
– Literal Object
– All Literal attributes are Public
– All functions in object are public
– Single Object referenced for the whole lifecycle of the Same Page

– Close Function type Object
function myObject()
{
function fx1(){…} //Private function
reurn{ //Block containing all public return types
fx1:function(){…..}
}
};
var o1 = new myObject(); //Call Constructor on ‘Object’

– Function Object represented by variable

var obj = function(){
this.fx1(){….}; //Public function
this.fx2(){….};//Public function

function fx3(){…} //Private Function
};

var o1 = new obj(); //Call Constructor on ‘Object’

IIFE – Immediately-Invoked Function Expressions

(function(){….})(); //Implicitely Invocable Function Expression., Self-Executable JavaScript

jQuery Programming

$, jQuery Object (insatance)

jQuery Entrypoint
– Loaded with the Window.onLoad is invoked
$(document).ready(function(){
});

– Selctors
– Process of Invoking DOM element from the DOM Tree
– Originated from CSS Selectors

– ‘id’ selector
– Used to invoke an element using its ‘id’ attribute
– uses ‘#’ symbol
e.g.
<input type=text id=txt/>
$(“#txt”)

– ‘Tag’ selector
– Used to invoke element based on its tag
– uses ‘tagname’
– used to invoke multiple matching elements
– returns element collection

e.g.
<input type=text id=txt/>
$(“input”)

– ‘Class’ selector
– Used to invoke element based on ‘class’ attribute’s value
– uses ‘.’ symbol
– used to invoke multiple elements with matching ‘class’ attribute value
– returns element collection

e.g.
<input type=text id=txt class=’c1’/>
$(“.c1”)

Hybrid Selector Expressions

– All Inputs of type text

$(‘inut[type=”text”]’)

All Inputs having class value as c1

$(‘input.c1’)

UWorking with jQuery
– Event Functions
– Functions used to subscribe an event for element
– e.g. Click, MouseMove, Keypress, KeyDown,hover etc.

Functions used to Define Events
– bind(), live(), and delegate()
– All above are depricated
bind() : Used to associate an event to element statically availeble in DOM
– Generate a separate event subscription for every matching element in DOM.
live (), the parser has removed this function from jQuery 1.11.x onwards
– Generate a separate event subscription for every matching element in DOM plus all matching elements dynamically added in DOM.
delegate(), subscribe event once for all matching elements and add callback function in event Queue.

– jQuery 1.7.x +
.on() function, internally calls .delegate() and used to subscribe matching elemnet’s event once() and their callback in Queue.
-Used to propogate the same event for dynamically added matching elements in DOM.

//jQuery style for subscribing the event

$(“selector”).on(‘<blankspace separated list of events>’,callback);

//Javascript style for subscribing the event

document.getElemenetById(‘<id>’).addEventListener(‘Event’,callback,bool)

– Functions

– Used to
– Set values
– read values
– Set Behavior for HTML Elements
val(), text(), html(), addClass(), removeClass(), cls(), append(), appendTo().

Commucation Functions
– .ajax();


– filters
– Process of Invoking a specific elelemnt from its comntainer based on the elements state.
– :selected
– Return element which is selected
e.g. <option> of <select> element
– :checked
– Returns checkbox which is checked
– :even, :odd, :first, :last, :nth-child(index)

$.each(<array>, function (<index>, <single value from array>) {

});
jQuery Ajax

$.ajax();

Accepts following parameters

url: Url of External Service
type: The Request type method to be processed in server
– GET (Default), POST, PUT and DELETE
– GET: Used the Http Header for Request and Response COmmunication
– POST : Data is Passed in Http Body
– PUT : Used for Resource Update
– Id of resource is passed in Header
– Data to be updated is passed in Body
– DELETE : Used to Remove resource
– Id of the resource is passed in Header.
contenttype
– Mime Type representing the formate of Data in COmunications
– application/json;utf-8 (JSON) -> Default
– application-xml (XML)
– application/atom;x-octate-stream (Binary)
datatype: Datatype of the data passed to server
– json, xml, html, bin, img
headers: Contain an information of the header store in Http
– “AUTHORIZATION”
– if Basic Auth:
basic_+ bton(username:password)

headers:{“AUTHORIZATION”,”basic_”+bton(username:password) }

if Token Based Auth
headers:{“AUTHORIZATION”,”bearer_”+{grant-type:password,username,password} }
cache: true/false, used to cache data on the browser. (default is true)

$.ajax({
url:,
type:
datatype:,
contenttype:,
headers:{}
cache:
});

Return ‘promise’ object
– jqXhr
Functions by the promise object
done(function(resp){…}); Will be executed when the Call is Successfully Completed

error(function(err){…}); Will be executed when the call is failed (Server Side Exception, resource not found, etc.)

$.ajax().done().error();

for PUT (Update)
$.ajax({
url: “http://<URL>&#8221; + EmpNo,
type: “PUT”,
data: Employee,
datatype: “json”,
ContentType:”application/json;utf-8″
}).done(function (resp) {
$(“#dvmsg”).html(‘Call Completed Successfully…’);
loadData();
}).error(function (err) {
$(“#dvmsg”).html(‘Call Failed…’ + err.status);
});

for DELETE

$.ajax({
url: “<URL>” + EmpNo,
type: “DELETE”,
}).done(function (resp) {

$(“#dvmsg”).html(‘Call Completed Successfully…’);
loadData();
}).error(function (err) {
$(“#dvmsg”).html(‘Call Failed…’ + err.status);
});


jQuery Plug-Ins OR Widgets

– Custom Extension to jQuery implmented using
– Custom utility Function
– Plug-In
– Custom utility UI Function
– Widget

AutoComplete
– Plug-In Widget function for TextBox
– ‘source’
– ENumeration
– Array
– Ajax Call
-DatePicker
– Calender Control with textBox
datePicker(options)

options
changeMonth: bool, allows to change month by providing <select> with the datePicker
changeYear : bool, allows to change year by providing <select> with the datePicker
Building Custom Plugin

Rules:
1. Must contains the Implicitely Invocable Function Expression (IIFE)
2. The IIFE must accept $ object
3. Use $.fn.<plug-In> to set the name for for the Plug-In

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s