SlideShare a Scribd company logo
1 of 41
Download to read offline
INTRODUCTION TO
F O R Z O MB I E S … … b y Z E E S H A N K H A N
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
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
Why jQuery?
• Lightweight
• Cross-browser support
• CSS-like syntax – easy for developers/nondevelopers to understand
• Active developer community
• Extensible – plugins
• And most importantly ‘Googlable’…
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();
Document Object Model
• The Document Object Model (DOM) is a crossplatform 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
Document Object Model
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>
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>
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
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
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") ) ;
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”);
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
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);
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.
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
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
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
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)
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://”
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();
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' );
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.
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’
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');
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>’);
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
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’);
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’});
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”
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);
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
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();
});
Specific Event Binding
blur
change
click
dblclick
error

focus
keydown
keypress
keyup
load

mousedown
mousemove
mouseout
mouseover
mouseup

resize
scroll
select
submit
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
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
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);
}
});
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);
});
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);

});
Ajax
$('#show').click(function(){
var prodId = $('#id').val();
$.post(
“/showResults.json",

When the button is clicked
Get the text box value
Ajax POST
URL

{id:prodId},

function(result) {
$('#detail').html(result);
}
);
});

The key/value to be passed

Update the "detail" div with
the result
Questions?

More Related Content

What's hot

Event In JavaScript
Event In JavaScriptEvent In JavaScript
Event In JavaScriptShahDhruv21
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Aaron Gustafson
 
Java: Primitive Data Types
Java: Primitive Data TypesJava: Primitive Data Types
Java: Primitive Data TypesTareq Hasan
 
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...Edureka!
 
jQuery - Chapter 3 - Effects
jQuery - Chapter 3 - Effects  jQuery - Chapter 3 - Effects
jQuery - Chapter 3 - Effects WebStackAcademy
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6Rob Eisenberg
 
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafSpring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafThymeleaf
 
ES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptWojciech Dzikowski
 
this keyword in Java.pptx
this keyword in Java.pptxthis keyword in Java.pptx
this keyword in Java.pptxParvizMirzayev2
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptWalid Ashraf
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Edureka!
 

What's hot (20)

React js
React jsReact js
React js
 
Selenium IDE LOCATORS
Selenium IDE LOCATORSSelenium IDE LOCATORS
Selenium IDE LOCATORS
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
 
Event In JavaScript
Event In JavaScriptEvent In JavaScript
Event In JavaScript
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
 
Java script ppt
Java script pptJava script ppt
Java script ppt
 
Java: Primitive Data Types
Java: Primitive Data TypesJava: Primitive Data Types
Java: Primitive Data Types
 
Modern JS with ES6
Modern JS with ES6Modern JS with ES6
Modern JS with ES6
 
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
 
jQuery - Chapter 3 - Effects
jQuery - Chapter 3 - Effects  jQuery - Chapter 3 - Effects
jQuery - Chapter 3 - Effects
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6
 
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafSpring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Angular
AngularAngular
Angular
 
Java
JavaJava
Java
 
ES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern Javascript
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
 
this keyword in Java.pptx
this keyword in Java.pptxthis keyword in Java.pptx
this keyword in Java.pptx
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
 

Viewers also liked

A Short Introduction To jQuery
A Short Introduction To jQueryA Short Introduction To jQuery
A Short Introduction To jQuerySudar Muthu
 
Informe general tema 2 maria laura coelho eslava
Informe general tema 2   maria laura coelho eslavaInforme general tema 2   maria laura coelho eslava
Informe general tema 2 maria laura coelho eslavaMARIACOELHO2016
 
Animate a Smarter UI: Tips for Motion on the Web
Animate a Smarter UI: Tips for Motion on the WebAnimate a Smarter UI: Tips for Motion on the Web
Animate a Smarter UI: Tips for Motion on the WebRobby Grant
 

Viewers also liked (6)

A Short Introduction To jQuery
A Short Introduction To jQueryA Short Introduction To jQuery
A Short Introduction To jQuery
 
JQuery - Effect - Animate method
JQuery - Effect - Animate methodJQuery - Effect - Animate method
JQuery - Effect - Animate method
 
D3.js and SVG
D3.js and SVGD3.js and SVG
D3.js and SVG
 
jQuery
jQueryjQuery
jQuery
 
Informe general tema 2 maria laura coelho eslava
Informe general tema 2   maria laura coelho eslavaInforme general tema 2   maria laura coelho eslava
Informe general tema 2 maria laura coelho eslava
 
Animate a Smarter UI: Tips for Motion on the Web
Animate a Smarter UI: Tips for Motion on the WebAnimate a Smarter UI: Tips for Motion on the Web
Animate a Smarter UI: Tips for Motion on the Web
 

Similar to Introduction to jQuery

Similar to Introduction to jQuery (20)

Jquery
JqueryJquery
Jquery
 
JQuery
JQueryJQuery
JQuery
 
Web technologies-course 11.pptx
Web technologies-course 11.pptxWeb technologies-course 11.pptx
Web technologies-course 11.pptx
 
FFW Gabrovo PMG - jQuery
FFW Gabrovo PMG - jQueryFFW Gabrovo PMG - jQuery
FFW Gabrovo PMG - jQuery
 
jQuery besic
jQuery besicjQuery besic
jQuery besic
 
Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD Combination
Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD CombinationLotusphere 2012 Speedgeeking - jQuery & Domino, a RAD Combination
Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD Combination
 
SEF2013 - A jQuery Primer for SharePoint
SEF2013 - A jQuery Primer for SharePointSEF2013 - A jQuery Primer for SharePoint
SEF2013 - A jQuery Primer for SharePoint
 
Getting started with jQuery
Getting started with jQueryGetting started with jQuery
Getting started with jQuery
 
jQuery Rescue Adventure
jQuery Rescue AdventurejQuery Rescue Adventure
jQuery Rescue Adventure
 
jQuery
jQueryjQuery
jQuery
 
jQuery Presentasion
jQuery PresentasionjQuery Presentasion
jQuery Presentasion
 
J query introduction
J query introductionJ query introduction
J query introduction
 
fuser interface-development-using-jquery
fuser interface-development-using-jqueryfuser interface-development-using-jquery
fuser interface-development-using-jquery
 
Jquery
JqueryJquery
Jquery
 
JavaScript!
JavaScript!JavaScript!
JavaScript!
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
Iniciando com jquery
Iniciando com jqueryIniciando com jquery
Iniciando com jquery
 
jQuery - Tips And Tricks
jQuery - Tips And TricksjQuery - Tips And Tricks
jQuery - Tips And Tricks
 
jQuery basics for Beginners
jQuery basics for BeginnersjQuery basics for Beginners
jQuery basics for Beginners
 
J query module1
J query module1J query module1
J query module1
 

Recently uploaded

Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 

Recently uploaded (20)

Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 

Introduction to jQuery

  • 1. INTRODUCTION TO F O R Z O MB I E S … … b y Z E E S H A N K H A N
  • 2. 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
  • 3. 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
  • 4. Why jQuery? • Lightweight • Cross-browser support • CSS-like syntax – easy for developers/nondevelopers to understand • Active developer community • Extensible – plugins • And most importantly ‘Googlable’…
  • 5. 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();
  • 6. Document Object Model • The Document Object Model (DOM) is a crossplatform 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
  • 8. 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>
  • 9. 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>
  • 10. 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
  • 11. 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
  • 12. 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") ) ;
  • 13. 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”);
  • 14. 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
  • 15. 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);
  • 16. 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.
  • 17. 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
  • 18. 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
  • 19. 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
  • 20. 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)
  • 21. 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://”
  • 22. 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();
  • 23. 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' );
  • 24. 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.
  • 25. 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’
  • 26. 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');
  • 27. 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>’);
  • 28. 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
  • 29. 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’);
  • 31. 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”
  • 32. 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);
  • 33. 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
  • 34. 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(); });
  • 35. Specific Event Binding blur change click dblclick error focus keydown keypress keyup load mousedown mousemove mouseout mouseover mouseup resize scroll select submit 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
  • 36. 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
  • 37. 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); } });
  • 38. 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); });
  • 39. 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); });
  • 40. Ajax $('#show').click(function(){ var prodId = $('#id').val(); $.post( “/showResults.json", When the button is clicked Get the text box value Ajax POST URL {id:prodId}, function(result) { $('#detail').html(result); } ); }); The key/value to be passed Update the "detail" div with the result