introduction to jquery

41
INTRODUCTION TO FOR ZOMBIES…… by ZEESHAN KHAN

Upload: zeeshan-khan

Post on 17-May-2015

918 views

Category:

Technology


1 download

DESCRIPTION

It provides a gentle introduction to jQuery, explaining the DOM structure, event handling in jQuery, selectors, utilities, ajax and lots more...

TRANSCRIPT

Page 1: Introduction to jQuery

INTRODUCTION TO FOR ZOMBIES…… by ZEESHAN KHAN

Page 2: Introduction to jQuery

OUTLINE

• Philosophy of jQuery

• Understanding the DOM

• The world of JavaScript events

• Bare-bones JavaScript vs. jQuery

• jQuery selectors, traversing and attributes

• jQuery manipulations, events and effects

• jQuery ajax

Page 3: Introduction to jQuery

What is jQuery?

An open-source library of JavaScript functions

Features

• Select and manipulate HTML

• Manipulate CSS

• JavaScript Effects and animations

• HTML DOM traversal and modification

• AJAX

• Utilities

Page 4: Introduction to jQuery

Why jQuery?

• Lightweight

• Cross-browser support

• CSS-like syntax – easy for developers/non-

developers to understand

• Active developer community

• Extensible – plugins

• And most importantly ‘Googlable’…

Page 5: Introduction to jQuery

How does it work?

jQuery() function

• Everything starts with a call to jQuery()

• Since it’s called so often, the $ variable is set up as an alias to jQuery()

Basic structure:

FindSomething.DoSomething

$(SomethingToFind).DoSomething();

Page 6: Introduction to jQuery

Document Object Model

• The Document Object Model (DOM) is a cross-

platform and language-independent convention for

representing and interacting with objects in HTML,

XHTML and XML documents.

• Represents the hierarchical structure of a web page

• You can add and subtract DOM elements on the fly

• You can change the properties and contents of DOM

elements on the fly

Page 7: Introduction to jQuery

Document Object Model

Page 8: Introduction to jQuery

Document Object Model

<html>

<head>

<title>Sample Document</title>

</head>

<body>

<h1>An HTML Document</h2>

<p>This is a <i>simple</i> document

</body>

</html>

Page 9: Introduction to jQuery

Traversing the DOM

• The <div> element is the parent of <ul>, and an ancestor of everything inside of it

• The <ul> element is the parent of both <li> elements, and a child of <div>

• The left <li> element is the parent of <span>, child of <ul> and a descendant of <div>

• The <span> element is a child of the left <li> and a descendant of <ul> and <div>

• The two <li> elements are siblings (they share the same parent)

• The right <li> element is the parent of <b>, child of <ul> and a descendant of <div>

• The <b> element is a child of the right <li> and a descendant of <ul> and <div>

Page 10: Introduction to jQuery

JavaScript Events

• Browsers are preprogrammed to recognize certain

actions such as clicking, page loading, mouse

movements etc.

• You write programs to respond to these events

• Two Step process

• Identify the element that you want to respond

to the event

• Assign an event and create a function to run

when event occurs

Page 11: Introduction to jQuery

JavaScript Events

• Mouse Events

Click, dblclick, mousedown, mouseup, mouseover,

mouseout, mousemove

• Document/Window Events

Load, resize

• Form Events

Submit, reset, change, focus, blur

• Keyboard Events

Keypress, keydown

Page 12: Introduction to jQuery

Bare-Bones JavaScript vs jQuery

• Example 1 -Hide an element with id "textbox“

//JavaScript

document.getElementById('textbox').style.display = "none";

//jQuery

$('#textbox').hide();

• Example 2 -Create a <h1> tag with "my text“

//JavaScript

var h1 = document.CreateElement("h1");

h1.innerHTML = "my text";

document.getElementsByTagName('body')[0].appendChild(h1);

//jQuery

$('body').append( $("<h1/>").html("my text") ) ;

Page 13: Introduction to jQuery

Bare-Bones JavaScript vs jQuery

• Example 3 -Add “myClass” class to <div> child of <a>

//JavaScript

var links = document.getElementsByTagName(‘a’), link;

for(i=0;i<links.length;i++) {

link = links[i];

for(j=0;j<link.children.length;j++) {

if(link.children[j].tagName === “DIV”) {

var currentClass = link.children[j].className;

var newClass;

newClass = currentClass === “” ? “newClass” : currentClass + “myClass”

link.children[j].className = newClass;

}

}

}

//jQuery

$(‘a > div’).addClass(“myClass”);

Page 14: Introduction to jQuery

The jQuery function

• jQuery() = $()

• $(function) The “Ready” handler

• $(‘selector’) Element selector expression

• $(element)Specify element(s) directly

• $(‘HTML’) HTML creation

• $.function() Execute a jQuery function

• $.fn.myfunc(){} Create jQuery function

Page 15: Introduction to jQuery

The Ready function

• Equivalent to window.onLoad function

• The codes written inside it are executed only after the DOM is “ready”

• 5 ways to specify the ready function

• jquery(document).ready(function(){…};);

• jquery().ready(function(){…};)

• jquery(function(){…};)

• jquery(dofunc);

• $(dofunc);

Page 16: Introduction to jQuery

Selectors

To find something, we can use common CSS syntax:

• $(css selector)

• This is known as a “selector”

• Returns a jQuery object containing an array of elements that match the selector

• The returned jQuery object is known as a “collection”, “wrapper” or “wrapped set”

The returned object contains a number of predefined methods that can act on the group of elements returned by selector.

Page 17: Introduction to jQuery

Selectors

$(‘img’)

Selects all images

$(‘p a’)

Selects all links nested under a paragraph

$(‘div.myClass’)

Selects all divs with a class of “myClass”

$(‘#myElement’)

Selects element with an id of “myElement”

$(‘#nav li.current a’)

Selects all links under any list item with class=“current” that

exist under the “nav” element

Page 18: Introduction to jQuery

Custom Selectors

:checkbox

Selects checkboxes

:checked

Selects checkboxes or radio buttons that are checked

:contains(foo)

Selects elements containing the text “foo”

:disabled

Selects disabled form elements

:input

Selects form elements (input, select, textarea, button)

:selected

Selects option elements that are selected

Page 19: Introduction to jQuery

Custom Selectors

:checkbox:checked:enabled

Selects checkboxes that are enabled and checked

input:not(:checkbox)

Selects non-checkbox <input> elements

div p:not(:hidden)

Selects all visible <p> elements nested under a div

Page 20: Introduction to jQuery

Position-based Selectors

:first :only-child :even and :odd

:last :nth-child(n) :eq(n)

:first-child :nth-child(even|odd) :gt(n)

:last-child :nth-child(Xn+Y) :lt(n)

• p:odd

Returns every odd paragraph element

• li:last

Returns last list item

• li:last-child

Returns last item of each list (last child of parent element)

• td:eq(2)

Returns third table cell

**Selectors start counting from 0 (except :nth-child, which starts from 1 for

CSS compatibility)

Page 21: Introduction to jQuery

Position-based Selectors

$(‘tr:nth-child(1)’)

Selects the first row of each table

$(‘tr:nth-child(even)')

Selects even numbered table rows

$(‘body > div:has(a)’)

Selects direct <div> children of <body> containing links

$(‘a[href*=jquery.com]’)

Matches all <a> elements that reference the jQuery site

$(‘a[href$=pdf]’)

Selects links to PDF files

$(‘a[href^=https://]’)

Selects all links starting with “https://”

Page 22: Introduction to jQuery

Traversing

• Gets the first list item on the page

var listItem = $( 'li' ).first(); // similar .last()

• Gets the siblings of the list item

var siblings = listItem.siblings();

• Gets the next sibling of the list item

var nextSibling = listItem.next(); // similar .prev()

• Gets the list item's parent

var list = listItem.parent();

Page 23: Introduction to jQuery

Traversing

• Gets the list items that are immediate children of the list

var listItems = list.children();

• Finds all ancestors of the list item that have a class of

"module"

var modules = listItem.parents( '.module' );

• Finds the closest ancestor of the list item that has a class

of "module"

var module = listItem.closest( '.module' );

• Gets ALL list items in the list, including nested ones

var allListItems = list.find( 'li' );

Page 24: Introduction to jQuery

The find method

Searches through a collection, returns a new set that

contains all elements that match a passed selector

expression

Powerful when combined with chaining:

$(‘p’).find(‘span’).fadeIn();

Starts with all paragraphs and searches for descendant

<span> elements

Same as $(‘p span’)

Internally the above selector calls the ‘find’ method so

performance-wise it would be preferable to use the ‘find’

method itself.

Page 25: Introduction to jQuery

The filter method

• Filters out elements from the collection

• Can accept a selector or a function as a parameter.

• Selector as parameter:

$(‘img’).addClass(‘test’)

.filter(‘[title*=dog]’)

.addClass(‘dogTest’)

Reduces set to images with a title attribute containing

‘dog’

Page 26: Introduction to jQuery

filter() vs find()

• filter() selects a subset of the already selected elements:

$('td').filter(expr)

Removes any <td> elements that don't match the

filter criteria

• find() selects a set of elements that are descendants of

the already selected elements

$('td').find('span')

Will find <span> elements inside <td> elements

Functionally similar to $('td span');

Page 27: Introduction to jQuery

Manipulating the DOM

$(‘#target’).before(‘<p>Inserted before #target</p>’);

$(‘#target’).after(‘<p>This is added after #target</p>’);

$(‘#target’).append(‘<p>Goes inside #target, at end</p>’);

$("span").appendTo("#target");

$(‘#target’).prepend(‘<p> #target goes inside it</p>’);

$("span").prependTo("#target");

$(‘#target’).wrap(‘<div></div>’);

Page 28: Introduction to jQuery

Chaining

• One of the most powerful features of jQuery is chaining

• jQuery commands (when finished with their action) return

the same group of elements, ready for another action

$(‘div.hideMe’).hide().addClass(‘removed’);

After the divs are hidden, we give them all a class

“removed”

• DOM operations can be expensive. No need to loop over

elements- All done behind the scenes

• Chains can continue indefinitely

Page 29: Introduction to jQuery

Attributes

• Get value (for first matching element):

var href = $(‘a.nav’).attr(‘href’);

• Set value:

$(‘a.nav’).attr(‘href’,’http://www.msn.com’);

• Remove attribute:

$(‘#intro’).removeAttr(‘id’);

Page 30: Introduction to jQuery

CSS

$(‘#intro’).addClass(‘highlighted’);

$(‘#intro’).removeClass(‘highlighted’);

$(‘#intro’).toggleClass(‘highlighted’);

$(‘div’).hasClass(‘highlighted’);

$(‘p’).css(‘font-size’, ‘20px’);

$(‘p’).css({‘font-size’:’20px’,

‘color’:’red’});

Page 31: Introduction to jQuery

Events

The DOM Event Model

• Multiple event handlers, or listeners, can be established on an element

• These handlers cannot be relied upon to run an any particular order

• When triggered, the event propagates from the top down (capture phase) or bottom up (bubble phase)

• IE doesn’t support the “capture phase”

Page 32: Introduction to jQuery

Basic syntax of Event binding

$(‘img’).bind(‘click’,function(event){

alert(‘Will this session ever end?? Arghh!!’);

});

$(‘img’).bind(‘click’,imgclick(event));

• Allows unbinding the function

$(‘img’).unbind(‘click’,imgclick());

$(‘img’).unbind(‘click’);

$(‘img’).one(‘click’,imgclick(event)); //only works once

$(‘img’).click(imgclick);

$(‘img’).toggle(click1, click2);

$(‘img’).hover(mouseover, mouseout);

Page 33: Introduction to jQuery

Event properties

event.target ref to element triggering event

event.target.id id of element triggering event

event.type type of event triggered

event.data second parm in the bind() func

Page 34: Introduction to jQuery

Event methods

• Cancel a default action and prevent it from bubbling:

$(‘form’).bind(‘submit’, function() {

return false;

})

• Cancel only the default action:

$(‘form’).bind(‘submit’, function(event){

event.preventDefault();

});

• Stop only an event from bubbling:

$(‘form’).bind(‘submit’, function(event){

event.stopPropagation();

});

Page 35: Introduction to jQuery

Specific Event Binding

blur focus mousedown resize

change keydown mousemove scroll

click keypress mouseout select

dblclick keyup mouseover submit

error load mouseup unload

$(‘img’).keyup(function(event) {

alert(‘zzzzzzzzz’);

});

.trigger(eventType)

does not actually trigger the event, but calls the appropriate function

specified as the one tied to the eventType.

.click(), blur(), focus(), select(), submit()

With no parameter, invokes the event handlers, like trigger does, for all

the elements in the wrapped set

Page 36: Introduction to jQuery

Effects

Function Description

$(selector).hide() Hide selected elements

$(selector).show() Show selected elements

$(selector).toggle()Toggle (between hide and show)

selected elements

$(selector).slideDown() Slide-down (show) selected elements

$(selector).slideUp() Slide-up (hide) selected elements

$(selector).slideToggle()Toggle slide-up and slide-down of

selected elements

$(selector).fadeIn() Fade in selected elements

$(selector).fadeOut() Fade out selected elements

$(selector).fadeTo()Fade out selected elements to a given

opacity

$(selector).fadeToggle() Toggle between fade in and fade out

Page 37: Introduction to jQuery

Ajax

$.ajax({

url: ‘/getResults.json',

type: 'GET',

data: ‘id=abc',

success: function(data) {

//called when successful

$('#ajaxphp-results').html(data);

},

error: function(e) {

//called when there is an error

//console.log(e.message);

}

});

Page 38: Introduction to jQuery

Ajax

$.ajax({

url: ‘/getResults.json',

type: 'GET',

data: ‘id=abc',

})

.done (: function(data) {

//called when successful

$('#ajax-results').html(data);

})

.fail (: function(data) {

//called when there is an error

$('#ajax-results').html(data);

});

Page 39: Introduction to jQuery

Ajax

$.get(“url", { name: "John", time: "2pm" },

function(data){

alert("Data Loaded: " + data);

});

$.post(“url", { name: "John", time: "2pm" },

function(data){

alert("Data Loaded: " + data);

});

Page 40: Introduction to jQuery

Ajax

$('#show').click(function(){

var prodId = $('#id').val();

$.post(

“/showResults.json",

{id:prodId},

function(result) {

$('#detail').html(result);

}

);

});

When the button is clicked

Get the text box value

Ajax POST

URL

The key/value to be passed

Update the "detail" div with

the result

Page 41: Introduction to jQuery

Questions?