SlideShare a Scribd company logo
1 of 89
jQuery
Mohammad Usman
Salesforce Consultant & Architect
Introduction to jQuery
What is jQuery?
What is jQuery?
• A cross-browser library of JavaScript functions.
• jQuery is a lightweight, open-source JavaScript library
that simplifies interaction between HTML and JavaScript
• It was and still being developed by John Resig from
Mozilla and was first announced in January 2006
• Features
• Select and manipulate HTML
• Manipulate CSS
• JavaScript Effects and animations
• HTML DOM traversal and modification
• AJAX
How jQuery Works
• The jQuery syntax is used to select HTML elements and
perform some action on those element(s).
• Basic syntax is: $(selector).action()
• A dollar sign to define jQuery
• A (selector) to find HTML elements
• An action() to be performed on the element(s)
Getting Started
• Download jQuery
• http://code.jquery.com/jquery-latest-version.js
• Rename to jquery-versionName.js
• Save
• Put it in Static Resources
• Create a test page “JquerySelectorExample”
• Edit the src/value attribute in the script tag
• Register a ready event
OR
<script src=“jquery.js”/>
Reference it in your markup
<apex:includeScript value=
“{!$Resource.jqueryVersion}”/>
<script src=“http://ajax.googleapis.com/
ajax/libs/jquery/1.8.1/
jquery.min.js”>
</script>
You can also reference it from Google
jQuery Core Concepts
Create HTML elements on the fly
var el = $(“<div/>”)
The Magic $() function
Manipulate existing DOM elements
$(window).width()
The Magic $() function
Selects document elements
(more in a moment…)
$(“div”).hide();
$(“div”, $(“p”)).hide();
The Magic $() function
$(document).ready(function(){…});
Fired when the document is ready for
programming.
Better use the full syntax:
$(function(){…});
The Magic $() function
It may be used in case of conflict with other
frameworks.
jQuery(“div”);
The full name of $() function is
jQuery uses closures for isolation
(function(){
var
jQuery=window.jQuery=window.$=function(){
// …
};
})();
The library is designed to be isolated
var f$ = jQuery.noConflict();
// now foo() is the jQuery main function
f$(“div”).hide();
Avoid $() conflict with other frameworks
// remove the conflicting $ and jQuery
var f$ = jQuery.noConflict(true);
$(“div”).hide()
$(“span”).appendTo(“body”)
$(“:button”).click()
jQuery’s programming philosophy is:
GET >> ACT
$(“div”).show()
.addClass(“main”)
.html(“Hello jQuery”);
Almost every function returns jQuery,
which provides a fluent programming
interface and chainability:
Comparison
• Compare the following:
What are the
advantages
of the jQuery
method?
$("a").click(function(){
alert("You clicked a link!");
});
<a href="" onclick="alert(‘You clicked a link!')">Link</a>
Get > Act
Chainability
The $() function
Three Major Concepts of jQuery
jQuery Selectors
$(“*”) // find everything
All Selector
Selectors return a pseudo-array of jQuery
elements
$(“div”)
// <div>Hello jQuery</div>
Basic Selectors
Yes, jQuery implements CSS Selectors!
$(“#usr”)
// <span id=“usr”>John</span>
$(“.menu”)
// <ul class=“menu”>Home</ul>
By Tag:
By ID:
By Class:
$(“div.main”) // tag and class
$(“table#data”) // tag and id
More Precise Selectors
// find by id + by class
$(“#content, .menu”)
// multiple combination
$(“h1, h2, h3, div.content”)
Combination of Selectors
$(“table td”) // descendants
$(“tr > td”) // children
$(“label + input”) // next
$(“#content ~ div”) // siblings
Hierarchy Selectors
$(“tr:first”) // first element
$(“tr:last”) // last element
$(“tr:lt(2)”) // index less than
$(“tr:gt(2)”) // index gr. than
$(“tr:eq(2)”) // index equals
Selection Index Filters
$(“div:visible”) // if visible
$(“div:hidden”) // if not
Visibility Filters
$(“div[id]”) // has attribute
$(“div[dir=‘rtl’]”) // equals to
$(“div[id^=‘main’]”) // starts with
$(“div[id$=‘name’]”) // ends with
$(“a[href*=‘msdn’]”) // contains
Attribute Filters
$(“input:checkbox”) // checkboxes
$(“input:radio”) // radio buttons
$(“:button”) // buttons
$(“:text”) // text inputs
Forms Selectors
$(“input:checked”) // checked
$(“input:selected”) // selected
$(“input:enabled”) // enabled
$(“input:disabled”) // disabled
Forms Filters
$(“select[name=‘ddl’] option:selected”).val()
Find Dropdown Selected Item
<select name=“cities”>
<option value=“1”>Tel-Aviv</option>
<option value=“2” selected=“selected”>Yavne</option>
<option value=“3”>Raanana</option>
</select>
SELECTORS DEMO
Manipulating CSS
Examples
$("button").click(function(){
alert($("p").css("color"));
});
$("button").click(function(){
$("p").css({
"color":"white",
"background-color":"#98bf21",
"font-family":"Arial",
"font-size":"20px",
"padding":"5px"
});
});
$("button").click(function(){
alert($("p").css("color"));
});
Challenge
• Highlight (background-color = yellow) any paragraph that
is double-clicked
<script>
$(document).ready(function(){
$("p").dblclick(function(){
$(this).css("background-color", "yellow");
});
});
</script>
MANIPULATING CSS
DEMO
Document Traversal
$(“div”).length
Returns number of selected elements.
It is the best way to check selector.
A Selector returns a pseudo array of
jQuery objects
$(“div”).get(2) or $(“div”)[2]
Returns a 2nd DOM element of the selection
Getting a specific DOM element
$(“div”).eq(2)
Returns a 2nd jQuery element of the selection
Getting a specific jQuery element
var sum = 0;
$(“div.number”).each(
function(){
sum += (+this.innerHTML);
});
this – is a current DOM element
each(fn) traverses every selected
element calling fn()
$(“table tr”).each(
function(i){
if (i % 2)
$(this).addClass(“odd”);
});
$(this) – convert DOM to jQuery
i - index of the current element
each(fn) also passes an indexer
.next(expr) // next sibling
.prev(expr) // previous sibling
.siblings(expr) // siblings
.children(expr) // children
.parent(expr) // parent
Traversing HTML
$(“table td”).each(function() {
if ($(this).is(“:first-child”)) {
$(this).addClass(“firstCol”);
}
});
Check for expression
// select paragraph and then find
// elements with class ‘header’ inside
$(“p”).find(“.header”).show();
// equivalent to:
$(“.header”, $(“p”)).show();
Find in selected
$(“<li><span></span></li>”) // li
.find(“span”) // span
.html(“About Us”) // span
.andSelf() // span, li
.addClass(“menu”) // span,li
.end() // span
.end() // li
.appendTo(“ul.main-menu”);
Advanced Chaining
$(“div”)
.slice(2, 5)
.not(“.green”)
.addClass(“middle”);
Get Part of Selected Result
HTML Manipulation
$(“p”).html(“<div>Hello $!</div>”);
// escape the content of div.b
$(“div.a”).text($(“div.b”).html());
Getting and Setting Inner Content
// get the value of the checked checkbox
$(“input:checkbox:checked”).val();
Getting and Setting Values
// set the value of the textbox
$(“:text[name=‘txt’]”).val(“Hello”);
// select or check lists or checkboxes
$(“#lst”).val([“NY”,”IL”,”NS”]);
Handling CSS Classes
// add and remove class
$(“p”).removeClass(“blue”).addClass(“red”);
// add if absent, remove otherwise
$(“div”).toggleClass(“main”);
// test for class existance
if ($(“div”).hasClass(“main”)) { //… }
// select > append to the end
$(“h1”).append(“<li>Hello $!</li>”);
// select > append to the beginning
$(“ul”).prepend(“<li>Hello $!</li>”);
Inserting new Elements
// create > append/prepend to selector
$(“<li/>”).html(“9”).appendTo(“ul”);
$(“<li/>”).html(“1”).prependTo(“ul”);
// select > replace
$(“h1”).replaceWith(“<div>Hello</div>”);
Replacing Elements
// create > replace selection
$(“<div>Hello</div>”).replaceAll(“h1”);
$(“h3”).each(function(){
$(this).replaceWith(“<div>”
+ $(this).html()
+ ”</div>”);
});
Replacing Elements while keeping the
content
// remove all children
$(“#mainContent”).empty();
Deleting Elements
// remove selection
$(“span.names”).remove();
// change position
$(“p”).remove(“:not(.red)”)
.appendTo(“#main”);
$(“a”).attr(“href”,”home.htm”);
// <a href=“home.htm”>…</a>
Handling attributes
// set the same as the first one
$(“button:gt(0)”).attr(“disabled”,
$(“button:eq(0)”).attr(“disabled));
// remove attribute - enable
$(“button”).removeAttr(“disabled”)
$(“img”).attr({
“src” : “/images/smile.jpg”,
“alt” : “Smile”,
“width” : 10,
“height” : 10
});
Setting multiple attributes
// get style
$(“div”).css(“background-color”);
CSS Manipulations
// set style
$(“div”).css(“float”, “left”);
// set multiple style properties
$(“div”).css({“color”:”blue”,
“padding”: “1em”
“margin-right”: “0”,
marginLeft: “10px”});
// get window height
var winHeight = $(window).height();
// set element height
$(“#main”).height(winHeight);
//.width() – element
//.innerWidth() – .width() + padding
//.outerWidth() – .innerWidth() + border
//.outerWidth(true) – including margin
Dimensions
The default unit is Pixel (px)
// from the document
$(“div”).offset().top;
// from the parent element
$(“div”).position().left;
// scrolling position
$(window).scrollTop();
Positioning
Events
$(document).ready(function(){
//…
});
When the DOM is ready…
• The document.ready() function executes when the
document is finished loading
• Defining jQuery functions inside document.ready()
prevents them from executing prematurely
• Fires when the document is ready for programming.
• Uses advanced listeners for detecting.
• window.onload() is a fallback.
// execute always
$(“div”).bind(“click”, fn);
// execute only once
$(“div”).one(“click”, fn);
Attach Event
Possible event values:
blur, focus, load, resize, scroll, unload, beforeunload,
click, dblclick, mousedown, mouseup, mousemove,
mouseover, mouseout, mouseenter, mouseleave,
change, select, submit, keydown, keypress, keyup,
error
(or any custom event)
jQuery.Event object
$(“div”).unbind(“click”, fn);
Detaching Events
(Unique ID added to every attached function)
$(“div”).trigger(“click”);
Events Triggering
Triggers browser’s event action as well.
Can trigger custom events.
Triggered events bubble up.
// attach / trigger
elem.blur(fn) / elem.blur()
elem.focus(fn) / elem.focus()
elem.click(fn) / elem.click()
elem.change(fn) / elem.change()
Events Helpers
And many others…
// use different triggering function
$(“div”).triggerHandler(“click”);
Preventing Browser Default Action
// prevent default action in handler
function clickHandler(e) {
e.preventDefault();
}
// or just return false
function clickHandler(e) {return false;}
// stop bubbling, keep other handler
function clickHandler(e) {
e.stopPropagation();
}
Preventing Bubbling
// stop bubbling and other handlers
function clickHandler(e) {
e.stopImmediatePropagation();
}
// or just return false
function clickHandler(e) {return false;}
// attach live event
(“div”).live(“click”, fn);
// detach live event
(“div”).die(“click”, fn);
Live Events
Currently supported events:
click, dblclick, mousedown, mouseup, mousemove,
mouseover, mouseout, keydown, keypress, keyup
EVENTS DEMO
Effects
// just show
$(“div”).show();
// reveal slowly, slow=600ms
$(“div”).show(“slow”);
// hide fast, fast=200ms
$(“div”).hide(“fast”);
// hide or show in 100ms
$(“div”).toggle(100);
Showing or Hiding Element
$(“div”).slideUp();
$(“div”).slideDown(“fast”);
$(“div”).slideToggle(1000);
Sliding Elements
$(“div”).fadeIn(“fast”);
$(“div”).fadeOut(“normal”);
// fade to a custom opacity
$(“div”).fadeTo (“fast”, 0.5);
Fading Elements
Fading === changing opacity
$(“div”).hide(“slow”, function() {
alert(“The DIV is hidden”);
});
$(“div”).show(“fast”, function() {
$(this).html(“Hello jQuery”);
}); // this is a current DOM element
Detecting animation completion
Every effect function has a (speed, callback)
overload
// .animate(options, duration)
$(“div”).animate({
width: “90%”,
opacity: 0.5,
borderWidth: “5px”
}, 1000);
Custom Animation
$(“div”).animate({width: “90%”},100)
.animate({opacity: 0.5},200)
.animate({borderWidth: “5px”});
Chaining Animation
By default animations are queued and than
performed one by one
$(“div”)
.animate({width: “90%”},
{queue:false, duration:1000})
.animate({opacity : 0.5});
Controlling Animations Sync
The first animation will be performed
immediately without queuing
EFFECTS DEMO
Extending the Library
// definition
jQuery.fn.printLine = function(s) {
return jQuery(this).each(function() {
this.append(“<div>”+ s +“</div>”);
});
};
// usage
$(“#log”).printLine(“Hello”);
Adding Methods
Do not use $ in the method
(at least not until next slide)
(function ($) {
jQuery.fn.printLine = function(s) {
return $(this).each(function() {
this.append(“<div>”+ s +“</div>”);
});
};
})(jQuery);
Closure to solve the $ issue
$.expr[‘:’].test = function(o, i, m, s) {
// o – current object in the selection
// i – loop index in the stack
// m – meta data about your selector
// s – stack of all the elements
// return true to include the element
// return false to exclude the element
};
Custom Selectors
LIBRARY EXTENSION
DEMO
Resources
• http://jquery.com/
• http://www.w3schools.com/jquery
• http://jqueryui.com/
• http://jquery.somee.com/
• Check out the demos and learn!
THANKS

More Related Content

What's hot

jQuery 1.7 Events
jQuery 1.7 EventsjQuery 1.7 Events
jQuery 1.7 Events
dmethvin
 

What's hot (20)

jQuery Rescue Adventure
jQuery Rescue AdventurejQuery Rescue Adventure
jQuery Rescue Adventure
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
JQuery introduction
JQuery introductionJQuery introduction
JQuery introduction
 
Jquery-overview
Jquery-overviewJquery-overview
Jquery-overview
 
SharePoint and jQuery Essentials
SharePoint and jQuery EssentialsSharePoint and jQuery Essentials
SharePoint and jQuery Essentials
 
Jquery introduction
Jquery introductionJquery introduction
Jquery introduction
 
jQuery 1.7 Events
jQuery 1.7 EventsjQuery 1.7 Events
jQuery 1.7 Events
 
jQuery Essentials
jQuery EssentialsjQuery Essentials
jQuery Essentials
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
jQuery Loves Developers - Oredev 2009
jQuery Loves Developers - Oredev 2009jQuery Loves Developers - Oredev 2009
jQuery Loves Developers - Oredev 2009
 
Prototype & jQuery
Prototype & jQueryPrototype & jQuery
Prototype & jQuery
 
Learning jQuery made exciting in an interactive session by one of our team me...
Learning jQuery made exciting in an interactive session by one of our team me...Learning jQuery made exciting in an interactive session by one of our team me...
Learning jQuery made exciting in an interactive session by one of our team me...
 
Learning jQuery in 30 minutes
Learning jQuery in 30 minutesLearning jQuery in 30 minutes
Learning jQuery in 30 minutes
 
J query1
J query1J query1
J query1
 
jQuery: Nuts, Bolts and Bling
jQuery: Nuts, Bolts and BlingjQuery: Nuts, Bolts and Bling
jQuery: Nuts, Bolts and Bling
 
J query b_dotnet_ug_meet_12_may_2012
J query b_dotnet_ug_meet_12_may_2012J query b_dotnet_ug_meet_12_may_2012
J query b_dotnet_ug_meet_12_may_2012
 
J query
J queryJ query
J query
 
jQuery
jQueryjQuery
jQuery
 
jQuery Presentation
jQuery PresentationjQuery Presentation
jQuery Presentation
 
A Short Introduction To jQuery
A Short Introduction To jQueryA Short Introduction To jQuery
A Short Introduction To jQuery
 

Similar to jQuery Presentasion

presentation_jquery_ppt.pptx
presentation_jquery_ppt.pptxpresentation_jquery_ppt.pptx
presentation_jquery_ppt.pptx
azz71
 

Similar to jQuery Presentasion (20)

Jquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript BasicsJquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript Basics
 
How to increase Performance of Web Application using JQuery
How to increase Performance of Web Application using JQueryHow to increase Performance of Web Application using JQuery
How to increase Performance of Web Application using JQuery
 
jQuery
jQueryjQuery
jQuery
 
Introducing jQuery
Introducing jQueryIntroducing jQuery
Introducing jQuery
 
Introduzione JQuery
Introduzione JQueryIntroduzione JQuery
Introduzione JQuery
 
Jquery presentation
Jquery presentationJquery presentation
Jquery presentation
 
jQuery - Tips And Tricks
jQuery - Tips And TricksjQuery - Tips And Tricks
jQuery - Tips And Tricks
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
presentation_jquery_ppt.pptx
presentation_jquery_ppt.pptxpresentation_jquery_ppt.pptx
presentation_jquery_ppt.pptx
 
jQuery Basic API
jQuery Basic APIjQuery Basic API
jQuery Basic API
 
jQuery besic
jQuery besicjQuery besic
jQuery besic
 
Jquery Basics
Jquery BasicsJquery Basics
Jquery Basics
 
Jquery
JqueryJquery
Jquery
 
JavaScript JQUERY AJAX
JavaScript JQUERY AJAXJavaScript JQUERY AJAX
JavaScript JQUERY AJAX
 
A Rich Web Experience with jQuery, Ajax and .NET
A Rich Web Experience with jQuery, Ajax and .NETA Rich Web Experience with jQuery, Ajax and .NET
A Rich Web Experience with jQuery, Ajax and .NET
 
JQuery
JQueryJQuery
JQuery
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
22 j query1
22 j query122 j query1
22 j query1
 
A Rich Web experience with jQuery, Ajax and .NET
A Rich Web experience with jQuery, Ajax and .NETA Rich Web experience with jQuery, Ajax and .NET
A Rich Web experience with jQuery, Ajax and .NET
 
jQuery basics
jQuery basicsjQuery basics
jQuery basics
 

jQuery Presentasion

Editor's Notes

  1. Separation of structure (HTML) and behavior (JS) We don’t need an onclick for every element