What You Should Already Know
Before you start jQuery, you need a basic knowledge of:- HTML
- CSS
- JavaScript
Intended audience:
Who should probably not attend this session?
If you do not have basic idea of web development (HTML, CSS, Java Script)Who have basic knowledge of jQuery (Cause this session will just introduction to jQuery)
Software requirements
You need a text editor, a browser and the jQuery library.Text editors:
TextPad
| |
Notepad++(Reccomended)
| |
Edit Plus
|
Browsers (Recommend Google Chrome or Firefox):
Google Chrome
| |
Firefox’s Firebug
| |
Safari
| |
Internet Explorer 8
| |
Internet Explorer 9
| |
Opera’s Dragonfly
|
jQuery library:
jQuery
|
What is JavaScript?
JavaScript is a scripting language that was designed for use within a web browser. Typically, JavaScript is used for interface interactions. Slideshows and other interactive components are typically done using JavaScript.
What is jQuery?
jQuery is a lightweight, "write less, do more", JavaScript library.
jQuery is an open source, cross-browser, CSS3 compliant JavaScript library that has made client side scripting relatively easier. It can produce dynamic web pages as well as Flash-like animations. jQuery today powers over 55% of the 10,000 most visited websites on the internet.
jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation.
The jQuery library contains the following features:
HTML/DOM manipulation
CSS manipulation
HTML event methods
Effects and animations
AJAX
Utilities
Why jQuery?
- It comes with MIT License (http://opensource.org/licenses/MIT) and is open source.
- Cross-browser Compatibility
- Fast & Small Footprint
- Short Learning curve & Great Documentation (http://docs.jquery.com)
- Tons of Plugins and Helpful Utilities(jQuery UI)
- CSS3 Selectors Compliant
- Widespread Adoption
- Bugs free or fixed pretty quick
Why not jQuery?
jQuery is easy to accomplish, but not always easy to implement as compared to, say, CSS.
Even though it is swift, the end product may not always be fast-paced.
You just have to get the version correct, and pray that you keep getting it correct.
If improperly used as a framework, things can get complicated beyond measure.
Before learning jQuery, let see how web page works:
How web pages works?
1. The browser requests a web page from a server when someone types a web address into the browser’s URL bar.
2. The server finds the requested file(s) and sends them to the browser
3. The browser displays a rendered HTML page based on the file sent from the server.
The power of script
To change your web pages on the fly, with an HTML tag known as <script>
Role of jQuery (and JavaScript)
Every browser comes with a built-in JavaScript interpreter that takes the directions you write in between the <script>tags and translates those directions into different kinds of action on the web page.
jQuery is a JavaScript library specialized for changing web page documents on the fly.
Components of Browser
Browser layout engine - The browser’s layout engine goes through the HTML and CSS to build a “document” using the HTML Document Object Model (DOM).
Browser viewport - The browser displays a rendered page in thebrowser’s viewport.
JS interpreter - The JS interpreter references the DOM to make changes to the web page without needing to reload it.
Hidden structure of a web page
HTML Tag:
Head:
The header of an HTML document where information about the document is placed. You must use the
title
element within the head element and meta
, style
, script
, base
and link
can also be used.
More Info about tags refer to: http://htmldog.com/reference/htmltags/
jQuery Installation:
Adding jQuery to Your Web Pages
There are several ways to start using jQuery on your web site. You can:
Download the jQuery library from jQuery.com
Include jQuery from a CDN, like Google
Downloading jQuery
There are two versions of jQuery available for downloading:
Production version
Development version
Steps needs to follow:
2. Find the section labeled “Grab the Latest Version!” Then, select the checkbox next to “Production.”.
3. Click the “Download jQuery” button.
4. The next page you’ll see will look something like this. Save the page into a folder called scripts on your drive
See figure:
What’s the difference between the Production and Development versions?
The Production version of jQuery is a minified version, intended for speed of execution on a web server.
The Development version is intended for developers interested in exploring and extending the inner workings of thejQuery library.
How to use downloaded jQuery library?
The jQuery library is a single JavaScript file, and you reference it with the HTML <script> tag (notice that the <script> tag should be inside the <head> section):
<head>
<script src="jquery-1.10.2.min.js"></script>
</head>
<script src="jquery-1.10.2.min.js"></script>
</head>
|
Do you wonder why we do not have type="text/javascript" inside the <script> tag?
This is not required in HTML5. JavaScript is the default scripting language in HTML5 and in all modern browsers! |
Alternatives to Downloading
If you don't want to download and host jQuery, you can include it from a CDN (Content Delivery Network). Both Google and Microsoft host jQuery.
To use jQuery from Google or Microsoft, use one of the following:
Google CDN:
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
</head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
</head>
Microsoft CDN:
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.2.min.js">
</script>
</head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.2.min.js">
</script>
</head>
|
One big advantage of using the hosted jQuery from Google or Microsoft
Many users already have downloaded jQuery from Google or Microsoft when visiting another site. As a result, it will be loaded from cache when they visit your site, which leads to faster loading time. Also, most CDN's will make sure that once a user requests a file from it, it will be served from the server closest to them, which also leads to faster loading time. |
Starting with jQuery (First program in jQuery):
Open your editor -> Create a new document ->Paste given code -> Save as MyFirstPage.html -> Open that page in Browser
*Note:- While saving select “save as type” as all type(“.”)
MyFirstPage.html
<!DOCTYPEhtml>
<html>
<head>
<title>jQuery goes to DOM-ville</title>
<style>
#change_me {
position: absolute;
top: 100px;
left: 400px;
font: 24px arial;
}
#move_up#move_down#color#disappear {
padding: 5px;
}
</style>
<script src="jquery.js" type="text/javascript">
</script>
</head>
<body>
<button id="move_up">Move Up</button>
<button id="move_down">Move Down</button>
<button id="color">Change Color</button>
<button id="disappear">Disappear/Re-appear</button>
<div id="change_me">Make Me Do Stuff!</div>
<script>
$(document).ready(function() {
$("#move_up").click(function() {
$("#change_me").animate({
top : 30
}, 200);
});//end move_up
$("#move_down").click(function() {
$("#change_me").animate({
top : 500
}, 2000);
});//end move_down
$("#color").click(function() {
$("#change_me").css("color", "purple");
});//end color
$("#disappear").click(function() {
$("#change_me").toggle("slow");
});//end disappear
});//end doc ready
</script>
</body>
</html>
How does that work?
The visitor clicks a button.
The JavaScript interpreter “hears” the click event and runs the function attached to it.
The JavaScript interpreter changes the DOM representation of the page.
The visitor sees the element move up the page.
Introducing the jQuery function (and shortcut)
The dollar sign with the parentheses is the shorter name of the jQuery function. This shortcut saves us from writing “jQuery()” every time we want to call the jQuery function. The jQuery function is also often referred to as the jQuery wrapper.
The short name and the long name point to the same thing: the big code block known as jQuery. Here are three different things you can put into the Query function.
Introduction to jQuery selectors
jQuery selects elements the same way CSS does
CSS selector
Element selector - This is an element selector (aka tag selector). It selects all of the h1 elements in the HTML document.
ID selector
Style, meet script
The great thing about jQuery is that it uses those same CSS selectors we use to style our page to manipulate elements on the page.
CSS selectors select elements to add style to those elements; jQuery selectors select elements to add behavior to those elements.
Illustration:
jQuery in translation:
To show you just how easy it is to learn jQuery, here’s a little breakdown of afew jQuery phrases to use when travelling in DOM country.
Furry Friends Campaign Example:
FurryFriendsCampaign.html
<!DOCTYPEhtml>
<html>
<head>
<title>Furry Friends Campaign</title>
<linkrel ="stylesheet"type="text/css" href="styles/my_style.css">
</head>
<body>
<divid="clickMe">Show me the theFurry Friend of the Day
</div>
<divid="picframe"> <imgsrc="images/furry_friend.jpg">
</div>
<scriptsrc="scripts/jquery-1.6.2.min.js">
</script> <script>
$(document).ready(function() {
$("#clickMe").click(function() {
$("img").fadeIn(1000);
$("#picframe").slideToggle("slow");
});
});
</script>
</body>
</html>
Illustration:
What we learn till now?
jQuery Syntax
The jQuery syntax is tailor made for selecting HTML elements and performing some action on the element(s).
Basic syntax is: $(selector).action()
A $ sign to define/access jQuery
A (selector) to "query (or find)" HTML elements
A jQueryaction() to be performed on the element(s)
Examples:
$(this).hide() - hides the current element.
$("p").hide() - hides all <p> elements.
$(".test").hide() - hides all elements with class="test".
$("#test").hide() - hides the element with id="test".
The Document Ready Event
You might have noticed that all jQuery methods in our examples are inside a document ready event:
$(document).ready(function(){
// jQuery methods go here...
});
// jQuery methods go here...
});
This is to prevent any jQuery code from running before the document is finished loading (is ready).
It is good practice to wait for the document to be fully loaded and ready before working with it. This also allows you to have your JavaScript code before the body of your document, in the head section.
Here are some examples of actions that can fail if methods are run before the document is fully loaded:
Trying to hide an element that is not created yet
Trying to get the size of an image that is not loaded yet
Tip: The jQuery team has also created an even shorter method for the document ready event:
$(function(){
// jQuery methods go here...
});
// jQuery methods go here...
});
Use the syntax you prefer. We think that the document ready event is easier to understand when reading the code
jQuery Selectors
jQuery selectors allow you to select and manipulate HTML element(s). jQuery selectors are used to "find" (or select) HTML elements based on their id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors.
All selectors in jQuery start with the dollar sign and parentheses: $().
The element Selector - The jQuery element selector selects elements based on the element name.
You can select all <p> elements on a page like this:
$("p")
Example
When a user clicks on a button, all <p> elements will be hidden:
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
$("button").click(function(){
$("p").hide();
});
});
The #id Selector - The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.
To find an element with a specific id, write a hash character, followed by the id of the element:
$("#test")
Example
When a user clicks on a button, the element with id="test" will be hidden:
$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});
$("button").click(function(){
$("#test").hide();
});
});
The .class Selector - The jQuery class selector finds elements with a specific class.
To find elements with a specific class, write a period character, followed by the name of the class:
$(".test")
Example
When a user clicks on a button, the elements with class="test" will be hidden:
$(document).ready(function(){
$("button").click(function(){
$(".test").hide();
});
});
$("button").click(function(){
$(".test").hide();
});
});
More Examples of jQuery Selectors:
Syntax
|
Description
|
$("*")
|
Selects all elements
|
$(this)
|
Selects the current HTML element
|
$("p.intro")
|
Selects all <p> elements with class="intro"
|
$("p:first")
|
Selects the first <p> element
|
$("ulli:first")
|
Selects the first <li> element of the first <ul>
|
$("ulli:first-child")
|
Selects the first <li> element of every <ul>
|
$("[href]")
|
Selects all elements with an href attribute
|
$("a[target='_blank']")
|
Selects all <a> elements with a target attribute value equal to "_blank"
|
$("a[target!='_blank']")
|
Selects all <a> elements with a target attribute value NOT equal to "_blank"
|
$(":button")
|
Selects all <button> elements and <input> elements of type="button"
|
$("tr:even")
|
Selects all even <tr> elements
|
$("tr:odd")
|
Selects all odd <tr> elements
|
selector.html
<html>
<head>
<title>the title</title>
<script type="text/javascript" src="jquery.js">
</script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
var pars = $("p");
for (i = 0; i < pars.length; i++) {
alert("Foundparagraph: " + pars[i].innerHTML);
}
});
</script>
</head>
<body>
<div>
<p class="myclass">This is a paragraph.</p>
<p id="myid">This is second paragraph.</p>
<p>This is third paragraph.</p>
</div>
</body>
</html>
Illustration of selection (Dig down with descendant selectors)
Descendant selectors are yet another selector we can use with jQuery, and they happen to fit our situation perfectly. With descendant selectors, we can specifyrelationships between elements. We can select children, parents, or siblings.

More info in Selectors:

.png)
Introduction to jQuery Event
What are Events?
All the different visitor's actions that a web page can respond to are called events.
An event represents the precise moment when something happens.
Examples:
- moving a mouse over an element
- selecting a radio button
- clicking on an element
The term "fires" is often used with events. Example: "The keypress event fires the moment you press a key".
Here are some common DOM events:
Mouse Events
Keyboard Events
Form Events
Document Events
Browser Events
.png)
Mouse Events
|
Keyboard Events
|
Form Events
|
Document/Window Events
|
click
|
keypress
|
submit
|
load
|
dblclick
|
keydown
|
change
|
resize
|
mouseenter
|
keyup
|
focus
|
scroll
|
mouseleave
|
blur
|
unload
|
jQuery Syntax For Event Methods
In jQuery, most DOM events have an equivalent jQuery method.
- To assign a click event to all paragraphs on a page, you can do this:
$("p").click();
- The next step is to define what should happen when the event fires. You must pass a function to the event:
$("p").click(function(){
// action goes here!!
});
// action goes here!!
});
Commonly Used jQuery Event Methods
- $(document).ready()
The $(document).ready() method allows us to execute a function when the document is fully loaded.
- click()
The click() method attaches an event handler function to an HTML element.
The function is executed when the user clicks on the HTML element.
The following example says: When a click event fires on a <p> element; hide the current <p> element:
Example
$("p").click(function(){
$(this).hide();
});
$(this).hide();
});
- dblclick()
The dblclick() method attaches an event handler function to an HTML element.
The function is executed when the user double-clicks on the HTML element:
Example
$("p").dblclick(function(){
$(this).hide();
});
$(this).hide();
});
- mouseenter()
The mouseenter() method attaches an event handler function to an HTML element.
The function is executed when the mouse pointer enters the HTML element:
Example
$("#p1").mouseenter(function(){
alert("You entered p1!");
});
alert("You entered p1!");
});
- mouseleave()
The mouseleave() method attaches an event handler function to an HTML element.
The function is executed when the mouse pointer leaves the HTML element:
Example
$("#p1").mouseleave(function(){
alert("Bye! You now leave p1!");
});
alert("Bye! You now leave p1!");
});
- mousedown()
The mousedown() method attaches an event handler function to an HTML element.
The function is executed, when the left mouse button is pressed down, while the mouse is over the HTML element:
Example
$("#p1").mousedown(function(){
alert("Mouse down over p1!");
});
alert("Mouse down over p1!");
});
- mouseup()
The mouseup() method attaches an event handler function to an HTML element.
The function is executed, when the left mouse button is released, while the mouse is over the HTML element:
Example
$("#p1").mouseup(function(){
alert("Mouse up over p1!");
});
alert("Mouse up over p1!");
});
- hover()
The hover() method takes two functions and is a combination of the mouseenter() and mouseleave() methods.
The first function is executed when the mouse enters the HTML element, and the second function is executed when the mouse leaves the HTML element:
Example
$("#p1").hover(function(){
alert("You entered p1!");
},
function(){
alert("Bye! You now leave p1!");
});
alert("You entered p1!");
},
function(){
alert("Bye! You now leave p1!");
});
- focus()
The focus() method attaches an event handler function to an HTML form field.
The function is executed when the form field gets focus:
Example
$("input").focus(function(){
$(this).css("background-color","#cccccc");
});
$(this).css("background-color","#cccccc");
});
- blur()
The blur() method attaches an event handler function to an HTML form field.
The function is executed when the form field loses focus:
Example
$("input").blur(function(){
$(this).css("background-color","#ffffff");
});
$(this).css("background-color","#ffffff");
});
More event reference: http://www.w3schools.com/jquery/jquery_ref_events.asp
jQuery events and functions
Event and Event listener:
How events are work?
Example:
$("#showMessage").click(function() {
alert('You Clicked Me!');
});
An element is clicked.
Binding an event
When we add an event to an element, we call this binding an event to that element. When we do this, the event listener knows to tell the JavaScript interpreter what function to call.
There are two ways of binding events to elements
- Method 1- We use this method to add events to elements as the page is getting loaded.
This is often known as the convenience method.
$("#myElement").click( function() {
alert($(this).text());
});
- Method 2 - We use this method just like Method 1, but we can also use it to add events to elements that get added to the page after it is loaded, like when we create new DOM elements.
$("#myElement").bind('click', function() {
alert($(this).text());
Method 1- the convenience method—is simply a shortcut for
Method 2- but only when the DOM elements exist already.
jQuery offers many shortcuts like this to help you keep your code cleaner.
They are known as convenience methods because they are included solely for ease of use—but they do have limits. You’ll want to use Method 2 to add events to new DOM elements that you create within your code, like if you added a new clickable image, or a new item to a list that you want the user to interact with.
Triggering events
Events can be triggered by a wide variety of things on any given page. In fact, your entire browser is eventful, and pretty much any part of it can trigger events!
$("#showMessage").click(function() {
alert('You Clicked Me!');
});
Removing an event
Just like binding events to elements, you often need to remove events from elements—for example, when you don’t want people to click a submit button twice on a form, or you only want to allow them to do something once on a page.
To remove one event:
The unbind command tells the web browser to no longer listen for this particular event for this element.
$("#myElement").unbind('click');
To remove all events:
$("#myElement").unbind();
So, an event listener sits inside the browser, attached to elements, waiting for events to happen, and tells the JavaScript interpreter to do something when they do happen.
Loop in jQuery
jQuery gives us the ability to loop through groups of elements, based on whatever selector we choose. Looping, also known as iteration, is simply going through a group of elements one at a time, and doing something to each element along the way.
$(".nav_item").each(function(){
$(this).hide();
});
Is your HTML file getting a little heavy on the script side there?
Including your own JavaScript/jQuery file
Including your own JavaScript/jQuery file is no different.
- Using your favorite text edito, create a file called my_scripts.js and save it in the scripts folder.
- Take all the JavaScript and jQuery code from our index.html file and move it into this new file. There is no need to put the <script> and </script> tags in the new file.1
$(document).ready(function() {
$(".guess_box").click( function() {
var my_num = Math.floor((Math.random()*5) + 5);
var discount = "<p>Your Discount is "+my_num+"%</p>";
$(this).append(discount);
$(".guess_box").each( function(){
$(this).unbind('click');
});
});
});
- Create the link to this file in your HTML page by putting the following code just before the closing </body> tag.
<script src="scripts/my_scripts.js"></script>
Example.html
<!DOCTYPE html>
<html>
<head>
<title>Jump for Joy</title>
<link href="styles/styles.css" rel="stylesheet">
</head>
<body>
<div id="header">
<h2>Jump for Joy Sale</h2>
</div>
<div id="main ">
<div class="guess_box">
<img src="images/jump1.jpg" />
</div>
<div class="guess_box">
<img src="images/jump2.jpg" />
</div>
<div class="guess_box">
<img src="images/jump3.jpg" />
</div>
<div class="guess_box">
<img src="images/jump4.jpg" />
</div>
</div>
<script src="scripts/jquery.1.6.2.min.js"></script>
<script src="scripts/my_scripts.js"></script>
</body>
<html>
Introduction to Function
Naming convention of functions
There are two ways to give names to functions.
- Function declaration - The first method is a function declaration, which defines a named function variable without requiring variable assignment.
function myFunc(){
$("div").hide();
}
- Function expression - A named function expression defines a function as part of a larger expression syntax (typically, a variable assignment):
var myFunc = function() {
$("div").show();
}
The anonymous function
Anonymous, or self-executing, functions don’t have a name, and they get called immediately when they’re encountered in the code. Also, any variables declared inside these functions are available only when the function is running.
$(document).ready(function() {
$(".guess_box").click(function() {
var my_num = Math.floor((Math.random() * 5) + 5);
var discount = "<p>Your Discount is " + my_num + "%</p>";
$(this).append(discount);
$(".guess_box").each(function() {
$(this).unbind('click');
});
});
});
Since we didn't give this function a name, we can’t call it from anywhere else in our code.
Named functions as event handlers
Earlier, we saw how anonymous functions can be used as handler functions for events. We can also use our own custom, named functions as these handlers, and call them directly from our code.
Example
var myFunc = function() {
$("div").show();
}
$("#myElement").click(myFunc);
Passing a variable to a function
When variables are added (or passed) into functions, they are known as arguments.
(Sometimes you may see them referred to as parameters too.) Let’s take a closer look at
how to pass an argument to a function.
function welcome (name) {
alert ("Hello"+ name);
}
// call our function
welcome("John");
Methods can change the CSS
class_test.html
<html>
<head>
<link href="styles/test_style.css" rel="stylesheet">
</head>
<body>
<div id="header" class="no_hover"><h1>Header</h1></div>
<button type="button" id="btn1">Click to Add</button>
<button type="button" id="btn2">Click to Remove</button>
<script src="scripts/jquery.1.6.2.js"></script>
<script src="scripts/my_test_scripts.js"></script>
</body>
</html>
my_test_scripts.js
$(document).ready(function() {
$("#btn1").click( function(){
$("#header").addClass("hover");
$("#header").removeClass("no_hover");
});
$("#btn2").click( function(){
$("#header").removeClass("hover");
$("#header").addClass("no_hover");
});
});
test_style.css
.hover{
border: solid #f00 3px;
}
.no_hover{
border: solid #000 3px;
}
jQuery web page manipulation
The DOM tree traverse
JavaScript interpreter in a browser can traverse (and then manipulate) the DOM, and jQuery is
especially good at it.
Traversal methods climb the DOM
.parent()
.children()
.prev()
.next()
$(".fish").parent()
in the fish class.
Then get the element
above those elements.
Select all the elements in
the menu_list class.
Then get the element
below those elements.
Select all the elements
in the fish class.
Then get the sibling element
immediately to the left.
Select all the elements
in the fish class.
Then get the sibling element
immediately to the right
Chain methods to climb farther
To go one parent higher, just add another method to the method chain.
Use filter methods to narrow your selections
Fortunately, jQuery provides filtering methods that let us narrow our
selection for problems like finding the first child. Let’s look at six of
them (three on this page, three on the next).
first
The first method will filter
out everything but the first element in a
selected set of elements.
eq
The eq method will filter out
everything but the element whose index
number is equal to what you put in
the parentheses in a selected set
of elements.
last
The last method will filter out
everything but the last element in a
selected set of elements.
Use filter methods to narrow your selections
slice
The slice method will filter out
everything but elements with an index
between the index numbers you put in its
parentheses.
$(".menu_list").children().slice(1,3);
filter The filter method will filter
out everything but elements that
match the selector you put in its
parentheses.
$(".menu_list").parents().filter(".organic")
not
The not method will filter out
everything that does not match the
selector you place in the parentheses.
$("ul.menu_list.organic").children().not(".local");
Detach
jQuery also offers us the detach method. detach and remove both take
elements out of the DOM.
$("img#thumbnail").remove();
$("img#thumbnail").detach();
jQuery Variable
$f = $(".fish").parent().parent().detach();
Putting a dollar sign in front of the
variable indicates that it’s storing elements
Store elements in an array
$f = $(".fish").parent().parent().detach();
Change out elements with replaceWith
The replaceWith method allows you to replace selected element(s) with new ones.
$("h2").replaceWith("<h1>My Menu</h1>");
Select all the h2
elements.
Replace the selected
elements with…
…the stuff in parentheses.
Insert HTML content into the DOM
before inserts content before the selected element.
after inserts content after the selected element.
$(".meat").before("<li>Tofu</li>");
0 comments:
Post a Comment