Getting Started with jQuery

71
Creating Web Applications using jQuery Akshay Mathur

description

This slide set was used for a online classroom session on jQuery.

Transcript of Getting Started with jQuery

Page 1: Getting Started with jQuery

Creating Web Applications

using jQuery

Akshay Mathur

Page 2: Getting Started with jQuery

Let’s Know Each Other

• Do you code?

• OS?

• Programing Language?

• HTML?

• JavaScript?

• JSON?

• Why are you attending?

Page 3: Getting Started with jQuery

Akshay Mathur

• Founding Team Member ofo ShopSocially (Enabling “social” for retailers)o AirTight Neworks (Global leader of WIPS)

• 15+ years in IT industryo Currently Principal Architect at ShopSociallyo Mostly worked with Startups

From Conceptualization to Stabilization At different functions i.e. development, testing, release With multiple technologies

Page 4: Getting Started with jQuery

Advance JavaScript

• As we try creating real world web applications, things go complex

• However, there immerges a pattern of requirementso Common functions can be created

Page 5: Getting Started with jQuery

JS Framework

• Library for simplifying JS coding

• Provides simple interface and syntactic sugar for common JS worko Selecting DOM elemento DOM traversal and manipulationo Event handlingo Takes care of cross browser and cross version issues

Page 6: Getting Started with jQuery

jQuery

• Jquery is most popular

• Takes care of cross browser and cross version issues

• Simplifys JS codingo Selectors for easy DOM traversalo Everything is via functionso Same function for get and seto …

Page 7: Getting Started with jQuery

jQuery Versions

• 2.x series doesn’t work on old IE browsero Do not use if you need to support

Internet Explorer 6.0 Internet Explorer 7.0 Internet Explorer 8.0

• 1.x series support old IE browsers

• Please carefully read jQuery download page http://jquery.com/download/

Page 8: Getting Started with jQuery

jQuery Function

• jQuery registers a function in global scopejquery()

• For convenience, this function is also mapped to a single character $

$()

Page 9: Getting Started with jQuery

jQuery Function

• This functions takes an argument of various types and returns jQuery objects

jquery(‘selector’)

$(DOM_element)

Page 10: Getting Started with jQuery

jQuery Object

• Always a list (Array)o Methods of Array work normally on jQuery object

$(‘’).length // 0o Members of the list are DOM elementso Empty list, if no element

• Native JavaScript methods and properties are o NOT available on jQuery Objectso Available on the members of the Array

$(‘img’)[0].src

Page 11: Getting Started with jQuery

jQuery Object

• Always has all API functionso No error on a function callo Does nothing, if the list in jQuery object is empty

$(‘’).text() //’’

$(‘’).html() //undefined

Page 12: Getting Started with jQuery
Page 13: Getting Started with jQuery

jQuery Selectors

Page 14: Getting Started with jQuery

Why Selectors

• Selecting a DOM element is needed for working on that elemento JavaScript has many functions like getElemetByID, getElementsByTagName etc.

• Instead, jQuery provides support of CSS selectors plus some jQuery specific selectorso Look at selectors page of jQuery API documentation for

complete list

Page 15: Getting Started with jQuery

Selectors

• Allows to select one or more DOM elementso Various selection patterns are available to useo Selector is passed as string to jQuery function

• When jQuery function is called on the selector, jQuery object is returnedo Selected nodes include the complete DOM tree under the

nodeo DOM manipulation can be done on the selected nodes

Page 16: Getting Started with jQuery

Basic Selectors

• All: ‘*’o Selects all nodes on the pageo Top level nodes e.g. html, head, body are also included

• Tag: ‘tagname’o Selects all nodes of a particular type e.g. div, a, span etc.

Page 17: Getting Started with jQuery

Basic Selectors

• ID: ‘#el_id’o Selects the node having the particular ID attribute o Does not work properly if there are more than one node

with same IDo This is equivalent to getElementById

• Class: ‘.el_class’o Selects all the nodes having the particular class attributeo This is equivalent to getElementsByClassName

Page 18: Getting Started with jQuery

@akshaymathu

Page 19: Getting Started with jQuery

Reading DOM

Page 20: Getting Started with jQuery

Reading innerHTML

$(el).html()

• Reads complete HTML inside a DOM nodeo Returns HTML of complete DOM tree including all child

nodeso All HTML tags and attributes are preservedo The output can be inserted somewhere else in the DOM

Page 21: Getting Started with jQuery

Reading innerText

$(‘selector’).text()

• Reads Text inside the selected DOM nodeo Returns text of complete DOM tree including all child

nodeso All HTML tags and attributes are removed

Page 22: Getting Started with jQuery

Advance Selectors

Page 23: Getting Started with jQuery

Combining Selectors

‘a.my_class’

Selects only the anchor nodes having having class my_class

What does following selects do? ‘span.clas1’‘table#my_tbl’

Page 24: Getting Started with jQuery

Combining Selectors

• Putting comma between selectors selects all of them

‘#el_id, .my_class’

o In this case node having id el_id as well as all nodes having class my_class will become part of returned jQuery object

Page 25: Getting Started with jQuery

Attribute Selectors

• Attribute selectors allow to create a selection based on any attribute of a HTML node

o Attribute Equals: “div[el_id=‘my_id’]”o Attribute Not Equals: “div[el_id!=‘my_id’]”o Attribute Starts with: “div[el_id^=‘my_id’]”o Attribute Ends with: “div[el_id$=‘my_id’]”o Attribute Contains: “div[el_id*=‘my_id’]”

• These work on custom (non-standard) attributes as well

Page 26: Getting Started with jQuery

Going Narrow

• Descendent: ‘#el_id a’o Selects all the anchors within the node having id=el_ido These anchors may be at any level deep in the DOM tree

• Children: ‘#el_id>.el_class’o Selects first level nodes having class=el_class within the

node having id=el_ido Only one level deep DOM tree is searched in this case

Page 27: Getting Started with jQuery
Page 28: Getting Started with jQuery

Filters

Page 29: Getting Started with jQuery

Narrowing Down Selection

• All possible ways to reach an element are not available as selectorso There are filters to further narrowing down

• Filters are applied on selectorso They can be part of selector stringo Filter functions can be used for filtering items selected

jQuey object

Page 30: Getting Started with jQuery

Form Filters

• All text boxes: ‘:text’

• Checked checkboxes: ‘:checkbox:checked’

• Buttons with class btn: ‘.btn:button’

• Everything disabled: ‘:disabled’

• Currently focused: ‘:focus’

Page 31: Getting Started with jQuery

Narrowing Down Selection

• All visible items: ‘:visiblle’

• First/Last: ‘a:first’, ‘a:last’

• Even rows: ‘tr:even’

• Nth column of a row: ‘tr.item>td:eq(N-1)’

• All header nodes: ‘:header’

Page 32: Getting Started with jQuery

Filter Functions

• Filter functions can be applied on existing jQuery objects for narrowing down

$(el).eq(index)o .eq() takes an index (0 based) as parameter and selects

only the item with specific index

$(el).find(selector)o .find() takes another selector as parametero It is used for selecting within a DOM tree instead of full

page

Page 33: Getting Started with jQuery

Selection Outside

• Sometimes it is needed to select parents of a DOM node

Immediate parents $(el).parent()

All parents up in the tree $(el).parents(selector)

Closest parent in the tree $(el).closest(selector)

Page 34: Getting Started with jQuery

34@akshaymathu

Page 35: Getting Started with jQuery

Manipulating DOM

Page 36: Getting Started with jQuery

Reading DOM

• Different functions are for reading different items

Contents of a DOM node$(el).text()$(el).html()

Attribute of an HTML node$(el).attr(‘attr_name’)$(el).css(‘style_attr_name’)

Form elements$(el).val()$(el).prop(‘property_name’)

Page 37: Getting Started with jQuery

Writing DOM

• Same functions are used for reading and writing

Contents of a DOM node$(el).text(‘some text’)$(el).html(‘some HTML’)

Attribute of an HTML node$(el).attr(‘attr_name’, ‘attr_value’)$(el).css(‘style_attr_name’, ‘value’)

Form elements$(el).val(‘Value’)$(el).prop(‘property_name’, true)

Page 38: Getting Started with jQuery

Adding and Removing Nodes

• Add inside$(el).append(html)$(el).prepend(html)

• Add outside$(el).before(html)$(el).after(html)

• Remove$(el).remove()

Page 39: Getting Started with jQuery

Changing Looks

• By changing in-line style$(el).css(‘property-name’,

‘property_value’)

• By changing class$(el).addClass(‘a_class’)$(el).removeClass(‘cls’)

Page 40: Getting Started with jQuery

Chaining

• Most jQuery functions return the jQuery objecto This allows to call multiple functions one after other as a

chain without having to select again

$(‘#a_id’).addClass(‘bold’).removeClass(‘heading’);

Page 41: Getting Started with jQuery
Page 42: Getting Started with jQuery

Dealing with User Actions

Page 43: Getting Started with jQuery

Triggering Event

• Browser raises the event on actions

• The events can also be programmatically triggered o By using .trigger() function$(el).trigger(‘change’);o By using the same shortcut function (that registers the

handler) without argument $(el).click();$(el).focus();

Page 44: Getting Started with jQuery

Handling Events

• On user’s action, browser raise corresponding evento Handler functions can be bind to the events

• All the handlers registered for the events get calledo Order in which the handlers (if more than one registered)

are called is not fixed

Page 45: Getting Started with jQuery

Binding Event Handlers

• The element on which the event handler is being bind has to be present in the DOM

$(el).on(‘click’, handler_fn);or

$(el).click(handler_fn);

• Event handlers can also be removed$(el).off(‘click’)

Page 46: Getting Started with jQuery

DOM Ready Event

• It is not safe to call a function that reads or writes DOM before the DOM is completely rendered

• So it is wise to write all the code in Ready Event handler

$(document).ready(function(){//Code goes here

});

Page 47: Getting Started with jQuery

Event Bubbling

• The raised event bubbles up in the HTML DOM tree till the root node

<body><ul>

<li><a href=“#”>Click Me</a>

</li></ul>

</body>

Page 48: Getting Started with jQuery

Event Delegation

• Because events bubble, they can be handled at any parent node in the DOM tree

<ul><li>

<a href=“#”>Click Me</a></li>

</ul>

• When user clicks on the link, click handlers registered at ‘a’, ‘li’ as well as at ‘ul’ will be fired

Page 49: Getting Started with jQuery

Delegated Event Handling

• This is useful if you want to attach a handler for an element that is going to be attached in DOM later

$(‘body’).click(function(ev){if ($(ev.target).is(‘a.yes’)){

handler();}

});or$(‘body’).on(‘click’, ‘a.yes’, handler)

Page 50: Getting Started with jQuery

Event Object

• For browser events, an Object having data about the event is passed to the event handlero The element that initiated the event

Ev.targeto Coordinates on the page where user acted

Ev.pageX and Ev.pageYo Code of keyboard key or mouse button

Ev.which

Page 51: Getting Started with jQuery

Testing Selection

$(el).is(selector)

• .is function is to test if output of one selector matches other selector

$(‘body’).click(function(ev){if ($(ev.target).is(‘a.yes’)){

handler();}

});

Page 52: Getting Started with jQuery

Event Bubbling

• The raised event bubbles up in the HTML DOM tree till the root nodeo This bubbling can be stopped within the even handler

$(a).click(function(ev){ev.stopPropagation();

});

Page 53: Getting Started with jQuery

Preventing Default Behavior

• By default browser does some default action when event occurso For example, when an anchor is clicked, it takes user to the

location specified by ‘href’

• This default behavior can be stopped in the event handler

$(a).click(function(ev){ev.preventDefault();

});

Page 54: Getting Started with jQuery
Page 55: Getting Started with jQuery

Talking to Server

Page 56: Getting Started with jQuery

Asynchronous JavaScript & XML

• A way in web browser to communicate with server without reloading the page

• XmlHttpRequest (XHR) object can also create HTTP request and receive responseo The request happens asynchronously

Other operations on page are allowed during the request

o Received data does not render automatically Data needs to be received in a callback function and

used programmatically

Page 57: Getting Started with jQuery

AJAX Call$.ajax({

url: ‘/my_ajax_target’,

type: ‘POST’,

DataType: ‘json’,

data: {id: 2},

context: this,

success: function(response){

alert(‘Hello! ‘ + response.name);

},

error: function(){

alert(‘Please try later’);

}

});

Page 58: Getting Started with jQuery

AJAX Types

• This parameter tells what HTTP method to use for the request

• GET and POST are supported by all browsero $.get(url) and $.post(url) can be used as

shortcut

• Some browsers do not support PUT and DELETEo For some web frameworks (e.g. pylons), POST with _method data parameter can be used as proxy

Page 59: Getting Started with jQuery

AJAX Data Types

• This parameter tells how to interpret the data returned from the servero ‘text’: Read as plain texto ‘xml’: Parse into XML documento ‘html’: Parse as HTMLo ‘script’: Interpret and execute as JavaScripto ‘json’: Convert into a JavaScript Objecto ‘jsonp’: Load as cross-domain script and convert into

JSON

Page 60: Getting Started with jQuery

AJAX Callbacks

• When AJAX events occur, callbacks registered for those evens are calledo Similar to all callbacks, the original context and variables

are lost by defaulto A context object can be passed using context parameter

$.ajax({

context: $(this).find(‘.greeting’),

success: function(response){

$(this).text(‘Hello! ‘ + response.name);

}});

Page 61: Getting Started with jQuery

AJAX Events

• There are may AJAX events for which handlers can be registeredo success: Called when AJAX call ends in successo error: Called when AJAX call ends in erroro complete: Called when AJAX call ends in success or in

erroro beforeSend: Called before sending the AJAX call

Page 62: Getting Started with jQuery
Page 63: Getting Started with jQuery

Animations and Effects

Page 64: Getting Started with jQuery

What is Animation

• Change in visual state (looks)

• Slow and smooth

Page 65: Getting Started with jQuery

Animation Effects

• jQuery’s standard show/hide functions also animateo If you pass time argument (in ms)o Animates the content by changing size of the content

Both height and width are changed

$(el).show(2000);

$(el).hide(2000);

Page 66: Getting Started with jQuery

Animation Effects

• Similar can be done by changing only heighto Easing name can be passed instead of time

o Hide

$(el).slideUp(‘slow’);

o Show

$(el).slideDown(‘fast’);

Page 67: Getting Started with jQuery

Animation Effects

• There are special functions for fade effecto Changes the opacity of the object

$(el).fadeOut(2000);

$(el).fadeIn(3000);

Page 68: Getting Started with jQuery

Animation Effects

• Any effect can be created using .animate()o Just pass desired set of CSS parameters as an object

$(el).animate({height: 10,opacity: 0.1}, 5000);

Page 69: Getting Started with jQuery

Chaining Animations

• Animation take some time to complete

• Second animation has to start after the first

• Callback functions can be passed to all animation functions

$(el).fadeOut(3000, function(){next_animation();

});

Page 70: Getting Started with jQuery

Movie in HTML

• Multiple animations in a sequence become a movieo Dialog add spice

• Hosted Movie: http://bit.ly/1c6Knuo

• Code: https://github.com/mathurakshay/movie

Page 71: Getting Started with jQuery

Thanks

@akshaymathu