2. WHAT IS JQUERY?
jQuery is a library of JavaScript Functions.
jQuery is a lightweight "write less, do more" JavaScript
library.
The jQuery library is stored as a single JavaScript file,
containing all the jQuery methods.
It can be added to a web page with the following mark-
up:
<head>
<script src="jquery.js"></script>
</head> 2
Mostafa Bayomi mos.bayomi@gmail.com
3. DOWNLOADING JQUERY
You can download jQuery library from
jQuery.com
If you don't want to store the jQuery library on your own computer,
you can use the hosted jQuery library from Google ,Microsoft or
jQuery website.
Google
<script type="text/javascript" src="
http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>
Microsoft
<script type="text/javascript" src="
http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js">
</script>
jQuery
<script type="text/javascript"
3
src=" http://code.jquery.com/jquery-latest.js">
</script>
Mostafa Bayomi mos.bayomi@gmail.com
4. HOW JQUERY WORKS?
The $() function is an alias for the jQuery() function .
This returns a special Java-Script object.
This JavaScript Object contains an array of DOM
elements that matches the selector.
Selector is key thing in jQuery development.
It is away to select node from DOM. This Java-Script
object possesses a large number of useful predefined
methods that can action group of elements.
4
Mostafa Bayomi mos.bayomi@gmail.com
5. HOW JQUERY WORKS?(CONT’D)
This type of construct is termed a wrapper because it
wraps the matching element(s) with extended
functionality.
Here $(object) is called jQuery wrapper around the
object.
jQuery has a ready element that checks
the document and waits until document is ready to be
manipulated.
It searches for the reference files for framework, once it
finds it then control goes to the function specified.
What ever code mentioned in the function that gets
5
executed. Event handling also can be implemented here.
Mostafa Bayomi mos.bayomi@gmail.com
6. STARTING WITH JQUERY
We load the Jquery library as any external JavaScript file.
script type="text/javascript" src="jquery.js"></script>
Now we loaded the Jquery library
As almost everything we do when using jQuery reads or
manipulates the document object model (DOM), we need to
make sure that we start adding events etc. as soon as the
DOM is ready.
To do this, we register a ready event for the document.
$(document).ready(function() {
// do stuff when DOM is ready
}); 6
Mostafa Bayomi mos.bayomi@gmail.com
7. JQUERY SYNTAX
The jQuery syntax is tailor made for selecting HTML
elements and perform some action on the element(s).
Basic syntax is: $(selector).action()
A dollar sign to define jQuery
A (selector) to "query (or find)" HTML elements
A jQuery action() to be performed on the element(s)
Examples:
$(this).hide() - hides current element
$("p").hide() - hides all paragraphs
$("p.test").hide() - hides all paragraphs with class="test"
$("#test").hide() - hides the element with id="test"
7
Mostafa Bayomi mos.bayomi@gmail.com
8. SELECTORS
With normal JavaScript, finding elements can be
extremely cumbersome, unless you need to find a
single element which has a value specified in the
ID attribute.
jQuery can help you find elements based on their
ID, classes, types, attributes, values of attributes
and much, much more.
It's based on CSS selectors and as you will see
after going through this tutorial, it is extremely
powerful.
8
Mostafa Bayomi mos.bayomi@gmail.com
9. SELECTORS(CONT’D)
You can instantiate the jQuery object simply by
writing jQuery() or even shorter using the jQuery
shortcut name: $(). Therefore, selecting a set of
elements is as simple as this:
$(<query here>)
With the jQuery object returned, you can then
start using and altering the element(s) you have
matched.
9
Mostafa Bayomi mos.bayomi@gmail.com
10. SELECT DOM ELEMENTS
Selecting DOM elements through document
based on the css selectors.
The #id selector
$(document).ready(function() {
$(“#d1").text("Test");
});
This code will be applied on only one element
whose ID attribute is d1.
10
Mostafa Bayomi mos.bayomi@gmail.com
11. SELECT DOM ELEMENTS(CONT’D)
The .class selector
$(document).ready(function() {
$(“.para").text("Test");
});
This code will be applied on all elements with the
.para class
11
Mostafa Bayomi mos.bayomi@gmail.com
12. SELECT DOM ELEMENTS(CONT’D)
The element selector
$(document).ready(function() {
$(“div").text("Test");
});
This code will be applied on all <div> tags
12
Mostafa Bayomi mos.bayomi@gmail.com
13. SELECT DOM ELEMENTS(CONT’D)
$(document).ready(function() {
$("#d2 span").text("Test");
});
This code will be applied on all span elements
within the element whose ID attribute is #d2.
$(document).ready(function() {
$("span.bold").text("Test");
});
This will match all span elements with "bold" as
the class
13
Mostafa Bayomi mos.bayomi@gmail.com
14. SOME MORE EXAMPLES
Syntax Description
$(this) Current HTML element
$("p") All <p> elements
$("p.intro") All <p> elements with class="intro"
$("p#intro") All <p> elements with id="intro"
$("p.intro:first") The first <p> element with class="intro"
$(".intro") All elements with class="intro"
$("#intro") The first element with id="intro"
$("ul li:first") The first <li> element of the first <ul>
$("ul li:first-child") The first <li> element of every <ul>
$("[href$='.jpg']") All elements with an href attribute that ends with
".jpg"
14
$("div#intro .head") All elements with class="head" inside a <div>
element with id="intro"
Mostafa Bayomi mos.bayomi@gmail.com
15. FIND ELEMENTS WITH A
SPECIFIC ATTRIBUTE
The most basic task when selecting elements
based on attributes is to find all the elements
which has a specific attribute.
The syntax for this selector is a set of square
brackets with the name of the desired attribute
inside it, for instance [name] or [href].
15
Mostafa Bayomi mos.bayomi@gmail.com
16. FIND ELEMENTS WITH A
SPECIFIC ATTRIBUTE(CONT’D)
Example.
$(document).ready(function() {
$(“[id]").text("Test");
});
We use the attribute selector to find all elements
on the page which has an id attribute and then
add text to it. As mentioned, this will match
elements with an id element no matter what
their value is 16
Mostafa Bayomi mos.bayomi@gmail.com
17. FIND ELEMENTS WITH A SPECIFIC
VALUE FOR A SPECIFIC ATTRIBUTE
Here's an example where we find elements with a
specific value:
<a href="http://www.google.com" target="_blank">Link 1</a>
<a href="http://www.google.com" target="_self">Link 2</a>
<a href="http://www.google.com" target="_blank">Link 3</a>
<script type="text/javascript">
$(function()
{
$("a[target='_blank']").text("new window");
});
</script> 17
Mostafa Bayomi mos.bayomi@gmail.com
18. FIND ELEMENTS WITH A SPECIFIC
VALUE FOR A SPECIFIC
ATTRIBUTE(CONT’D)
what if you're looking for all elements which don't
have the value? Inverting the selector is very easy:
$("a[target!='_blank']").append(" [same window]");
The difference is the != instead of =, a common way of
negating an operator within many programming
languages.
18
Mostafa Bayomi mos.bayomi@gmail.com
19. FIND ELEMENTS WITH A SPECIFIC
VALUE FOR A SPECIFIC
ATTRIBUTE(CONT’D)
And there's even more possibilities:
Find elements with a value which starts with a specific
string using the ^=operator:
$("input[name^='txt']").css("color", "blue");
Find elements with a value which ends with a specific
string using the $= operator:
$("input[name$='letter']").css("color", "red");
Find elements with a value which contains a specific
word: 19
$("input[name*='txt']").css("color", "blue");
Mostafa Bayomi mos.bayomi@gmail.com
20. PARENT/CHILD RELATION
SELECTORS
jQuery also allows you to select elements based on their
parent element. There are two variations:
One which will only match elements which are a direct child
to the parent element.
And one which will match all the way down through the
hierarchy, e.g. a child of a child of a child of a parent element.
20
Mostafa Bayomi mos.bayomi@gmail.com
21. PARENT/CHILD RELATION
SELECTORS(CONT’D)
The syntax for finding children which are direct
descendants of an element looks like this:
$("div > a")
This selector will find all links which are the direct child
of a div element.
Replacing the greater-than symbol with a simple space
will change this to match all links within a div element,
no matter if they are directly related or not:
21
$("div a")
Mostafa Bayomi mos.bayomi@gmail.com
22. JQUERY EVENTS
The jQuery event handling methods are core functions in jQuery.
Event handlers are method that are called when "something
happens" in HTML. The term "triggered (or "fired") by an event" is
often used.
$("button").click(function() {..some code... } )
EX:
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
22
Mostafa Bayomi mos.bayomi@gmail.com
23. JQUERY EVENTS(CONT’D)
Here are some examples of event methods in jQuery:
Event Method Description
$(document).ready(function) Binds a function to the ready event of a
document
(when the document is finished loading)
$(selector).click(function) Triggers, or binds a function to the click event of
selected elements
$(selector).dblclick(function) Triggers, or binds a function to the double click
event of selected elements
$(selector).focus(function) Triggers, or binds a function to the focus event
of selected elements
$(selector).mouseover(function) Triggers, or binds a function to the mouseover
event of selected elements
23
Mostafa Bayomi mos.bayomi@gmail.com
24. JQUERY EVENT HOVER() METHOD
Specifies a function to run when the mouseenter and mouseleave events
occur.
If only one function is specified, it will be run for both the mouseenter and
mouseleave events.
$(selector).hover(inFunction,outFunction)
$("p").hover(function(){
$("p").css("background-color","yellow");
},function(){
$("p").css("background-color","#E9E9E4");
});
24
Mostafa Bayomi mos.bayomi@gmail.com
25. JQUERY EVENT PAGEX, PAGEX
The pageX() property is the position of the mouse pointer, relative to the
left edge of the document.
$(document).mousemove(function(e){
$("span").text("X: " + e.pageX + ", Y: " + e.pageY);
});
25
Mostafa Bayomi mos.bayomi@gmail.com
26. FADING ELEMENTS
Doing simple animation is very easy with jQuery.
One of the effects it supports out-of-the-box, is fading an
element in and out of visibility using the fadeIn()
method.
$("#divTestArea1").fadeIn();
You can fade a lot of different elements, like divs, spans
or links.
The fadeIn() method can take up to three parameters.
26
Mostafa Bayomi mos.bayomi@gmail.com
27. FADING ELEMENTS(CONT’D)
The first one allows you to specify the duration of the
effect in milliseconds, or "fast" or "slow", which is the
same as specifying either 200 or 600 milliseconds.
$("#divTestArea21").fadeIn("fast");
$("#divTestArea22").fadeOut("slow");
$("#divTestArea23").fadeIn(2000);
27
Mostafa Bayomi mos.bayomi@gmail.com
28. FADING ELEMENTS(CONT’D)
The second parameter can either be the name of an
easing function.
Easing As of jQuery 1.4.3:
An optional string naming an easing function may be
used.
Easing functions specify the speed at which the
animation progresses at different points within the
animation.
The only easing implementations in the jQuery library
are the default, called swing, and one that progresses at
a constant pace, called linear.
More easing functions are available with the use of
28
plug-ins, most notably the jQuery UI suite.
Mostafa Bayomi mos.bayomi@gmail.com
29. FADING ELEMENTS(CONT’D)
The third parameter is a callback function that you
may supply, to be called once the effect is done.
$("#divTestArea3").fadeIn(2000, function()
{
$("#divTestArea3").fadeOut(3000);
});
29
Mostafa Bayomi mos.bayomi@gmail.com
30. FADING ELEMENTS(CONT’D)
There may be situations where you want to fade an
element in our out depending on its current state.
You could of course check if it is visible or not and then
call either fadeIn() or fadeOut(), but the nice jQuery
developers have supplied us with a specific method for
toggling an element, called fadeToggle().
It takes the same parameters as fadeIn() and fadeOut(),
so it's very easy to use.
$("#divTestArea4").fadeToggle("slow");
30
Mostafa Bayomi mos.bayomi@gmail.com
31. SLIDING ELEMENTS
sometimes a sliding effect is a better choice, and for
that, jQuery has a set of matching methods for doing
just that.
$("#divTestArea1").slideDown();
For hiding the box again, we can use the slideUp()
method. They both take the same set of parameters,
which are all optional.
$("#divTestArea21").slideDown("fast");
$("#divTestArea22").slideUp("slow");
$("#divTestArea23").slideDown(2000); 31
Mostafa Bayomi mos.bayomi@gmail.com
32. SLIDING ELEMENTS(CONT’D)
In case you want to simply slide an element up or down
depending on its current state, the jQuery developers
have provided us with a nice slideToggle() method for
doing just that.
$("#divTestArea4").slideToggle("slow");
32
Mostafa Bayomi mos.bayomi@gmail.com
33. CUSTOM ANIMATIONS WITH THE
ANIMATE() METHOD
With the animate() method, you can create custom
animations where you manipulate pretty much any
numerical CSS property of an element.
This allows you to e.g. move a box slowly across the
screen or have it jump up and down.
$("#divTestBox1").animate({"left" : "200px”});
The first, and only required, parameter of the animate
function is a map of the CSS properties that you wish to
have altered. In this case, we have an absolutely
positioned div element, which we tell jQuery to move 33
until it has reached a left property of 200 pixels.
Mostafa Bayomi mos.bayomi@gmail.com
34. CUSTOM ANIMATIONS WITH THE
ANIMATE() METHOD(CONT’D)
The second parameter allows you to specify the
duration of the animation in milliseconds or as "slow" or
"fast" which is the same as 600 or 200 ms.
$("#divTestBox1").animate({"left":"200px”},2000);
As the third parameter, we can specify a callback
function to be called once the animation is done. This
can be very useful for performing a number of different
animations in a row.
34
Mostafa Bayomi mos.bayomi@gmail.com
35. STOPPING ANIMATIONS WITH THE STOP()
METHOD
Sometimes you need to stop an animation before it
finishes, and for this, jQuery has the stop() method.
It works for all effects related jQuery functions, including
sliding, fading and custom animations with the animate()
method.
<a href="#“ onclick="$('#Testdiv1').slideDown(5000);">Show</
a>
<a href=“#" onclick="$('#Testdiv1').stop();">Stop</a>
When you click the first link, the slideDown() method is used on our
div element, starting a slow slide down. A click on the second link 35
will kill the current animation being performed on the selected
element.
Mostafa Bayomi mos.bayomi@gmail.com
36. STOPPING ANIMATIONS WITH THE STOP()
METHOD(CONT’D)
This is the default behavior of the stop() method, but
two optional parameters allows us to do things differently.
The first parameter specifies whether the animation
queue should be cleared or not.
The default is false, which means that only the active
animation will be stopped, allowing any queued
animations to be performed afterwards.
The second parameter tells jQuery whether you would
like for it to just stop where it is, or rush through the
animation instead, allowing for it to finish. 36
Mostafa Bayomi mos.bayomi@gmail.com
37. ADDING CSS
$("#cssSpan").css(“background–color”,“Yellow”)
This will add a css style to the element with the
#cssSpan id
To group more than one property:
$("#cssSpan").css(
{'background-color':'Yellow','color':'black’}
);
37
Mostafa Bayomi mos.bayomi@gmail.com
38. GETTING AND SETTING CSS CLASSES
it's equally easy to manipulate the CSS of elements.
jQuery gives you easy access to changing both the
style attribute, which you manipulate using the css()
method, as well as the class(es) of an element, where
several different methods lets you modify it.
38
Mostafa Bayomi mos.bayomi@gmail.com
39. GETTING AND SETTING CSS
CLASSES(CONT’D)
The class attribute takes one or several class names,
which may or may not refer to a CSS class defined in
your stylesheet.
Usually it does, but you may from time to time add
class names to your elements simply to be able to
reach them easily from jQuery, since jQuery has
excellent support for selecting elements based on their
class name(s).
addClass("bold")
removeClass("bold")
hasClass("bold")
39
Mostafa Bayomi mos.bayomi@gmail.com
40. GETTING AND SETTING CSS
CLASSES(CONT’D)
toggleClass()
With this method we can switch on/off the css class.
$("#test").toggleClass('heighlight');
And also we can add multiple classes for multiple
elements.
$("#test span, #test b").addClass("c1 c2");
Here we select the span and the b tags in the #test
and add c1 and c2 classes to them separated by a space
40
Mostafa Bayomi mos.bayomi@gmail.com
41. THE APPEND() AND PREPEND() METHODS
Adding new stuff to existing elements is very easy with
jQuery.
There are methods for appending or prepending, taking
HTML in string format, DOM elements and jQuery
objects as parameters.
$('#TestList').append('<li>Appended item</li>')
The new item will be inserted as the last tem
$('#TestList').prepend('<li>Appended item</li>')
The new item will be inserted as the first item of the list
41
Mostafa Bayomi mos.bayomi@gmail.com
42. THE APPEND() AND PREPEND()
METHODS(CONT’D)
both the append() and the prepend() method takes an
infinite amount of new elements as parameters.
var item1 = $("<li></li>").text("Item 1");
var item2 = "<li>Item 2</li>“;
var item3 = document.createElement("li");
item3.innerHTML = "Item 3“;
$("#TestList").append(item1, item2, item3);
42
Mostafa Bayomi mos.bayomi@gmail.com
43. THE APPENDTO() AND PREPENDTO()
METHODS
There are variations of the append() and prepend()
methods, called appendTo() and prependTo().
They do pretty much the same, but they do it the other
way around, so instead of calling them on the elements
you wish to append/prepend to, with a parameter of
what is to be appended/prepended, you do the exact
opposite.
$('#TestList').append('<li>Appended item</li>')
$('<li>Appended item</li>').appendTo('#TestList')
43
Mostafa Bayomi mos.bayomi@gmail.com
44. THE BEFORE() AND AFTER() METHODS
in some cases, you need to insert things before or after
one or several elements.
jQuery has the before() and after() methods for just
this purpose.
$('input.test1').before('<i>Before</i>')
An italic tag will be inserted before each input element on the page
using the "test1" class.
$('input.test1').after('<i>After</i>')
A bold tag will be inserted after each input element on the page
using the "test1" class. 44
Mostafa Bayomi mos.bayomi@gmail.com
45. THE BEFORE() AND AFTER()
METHODS(CONT’D)
Both after() and before() allows you to use HTML
strings, DOM elements and jQuery objects as
parameters and an infinite amount of them as well.
$("#spnTest2").after(element1, element2, element3);
There are variations of the before() and after() methods,
called insertBefore() and insertAfter().
$('#test').before('<i>Before</i>')
$('<i>Before</i>').insertBefore('#test')
45
Mostafa Bayomi mos.bayomi@gmail.com
46. THE REMOVE() AND EMPTY() METHODS
The remove() method will delete the selected element(s),
while the empty() method will only delete all child
elements of the selected element(s).
$("#test").remove();
$("#test").empty();
See the Example
46
Mostafa Bayomi mos.bayomi@gmail.com
47. THE REMOVE() AND EMPTY()
METHODS(CONT’D)
he remove() method comes with one optional parameter,
which allows you to filter the elements to be removed,
using any of the jQuery selector syntaxes.
You could of course achieve the same simply by doing
the filtering in your first selector, but in some
situations, you may be working on a set of already
selected elements.
$("#test b").remove(".bold");
See the Example
47
Mostafa Bayomi mos.bayomi@gmail.com
48. CHAINING IN JQUERY
Chaining is essential to writing good jQuery.
//without chaining
$("#menu").fadeIn('fast');
$("#menu").addClass(".active");
$("#menu").css('marginRight', '10px');
//with chaining
$("#menu").fadeIn('fast')
.addClass("active")
.css('marginRight', '10px');
48
Mostafa Bayomi mos.bayomi@gmail.com
49. CHAINING IN JQUERY(CONT’D)
jQuery methods return a jQuery object.
After you've run a method on your selection, you can
continue running more methods.
The obvious benefit is you write less code, But your code
also runs faster.
In the first snippet without chaining every single row
tells jQuery to first search the entire DOM for an object,
and then run a method on that object.
When we use chaining, jQuery only has to search for the
object one single time.
49
Mostafa Bayomi mos.bayomi@gmail.com
50. THE CHILDREN() METHOD
Given a jQuery object that represents a set of DOM elements,
the .children() method allows us to search through the
children of these elements in the DOM tree and construct a
new jQuery object from the matching elements.
The .children() method optionally accepts a selector
expression of the same type that we can pass to the $
() function.
If the selector is supplied, the elements will be filtered by
testing whether they match it.
NOTE:
The children() method only travels a single level down
the DOM tree 50
Mostafa Bayomi mos.bayomi@gmail.com
51. THE FIND() METHOD
It Is like the children() method.
Get the descendants of each element in the current set of
matched elements, filtered by a selector, jQuery object, or
element.
But the find() method can traverse down multiple levels
to select descendant elements
51
Mostafa Bayomi mos.bayomi@gmail.com
52. THE NEXT() METHOD
Get the immediately following sibling of each element in
the set of matched elements.
If a selector is provided, it retrieves the next sibling only
if it matches that selector.
Given a jQuery object that represents a set of DOM
elements, the .next() method allows us to search through
the immediately following sibling of these elements in the
DOM tree and construct a new jQuery object from the
matching elements.
52
Mostafa Bayomi mos.bayomi@gmail.com
53. THE NOT() METHOD
$(function() { $
("li").not(":has(ul)").css("border", "1px
solid black");
});
This selects all li elements that have a ul
element as a child and removes all elements from
the selection. Therefore all li elements get a
border, except the one that has a child ul.
53
Mostafa Bayomi mos.bayomi@gmail.com
54. THE END() METHOD
Most of jQuery's DOM traversal methods operate
on a jQuery object instance and produce a new
one, matching a different set of DOM elements.
When this happens, it is as if the new set of
elements is pushed onto a stack that is
maintained inside the object.
Each successive filtering method pushes a new
element set onto the stack.
If we need an older element set, we can use
end() to pop the sets back off of the stack.
54
Mostafa Bayomi mos.bayomi@gmail.com
55. THE END() METHOD
$('ul.first').find('.foo')
.css('background-color', 'red')
.end().find('.bar').css('background-color', 'green');
This chain searches for items with the class foo within
the first list only and turns their backgrounds red.
Then end() returns the object to its state before the call
to find().
So the second find() looks for '.bar' inside <ul
class="first">, not just inside that list's <li class="foo">,
55
and turns the matching elements' backgrounds green.
Mostafa Bayomi mos.bayomi@gmail.com
56. TRAVERSING METHODS
To see the rest of the traversing methods
(add(),andSelf(),children(),closest(),end(),not(),etc..)
please visit:
http://api.jquery.com/category/traversing/
56
Mostafa Bayomi mos.bayomi@gmail.com
57. JQUERY HEIGHT() AND WIDTH()
METHODS
jQuery has two important methods for size
manipulation.
height()
width()
Size Manipulation Examples
The height() method sets the height of all
matching elements:
Example
$("#div1").height("200px");
57
Mostafa Bayomi mos.bayomi@gmail.com
58. EVENTS
Events in JavaScript are usually something where you
write a snippet of code or a name of a function within
one of the event attributes on an HTML tag.
<a href="#" onclick="alert('Hello, world!');">Test</a>
And of course this is still perfectly valid when using
jQuery.
You can bind code to the event of an element even
easier, especially in cases where you want to attach
anonymous functions or use the same code for multiple
events, or even the same code for multiple events of 58
multiple elements.
Mostafa Bayomi mos.bayomi@gmail.com
59. EVENTS(CONT’D)
Example:
$("a, span").bind("click", function() {
alert('Hello, world!');
});
We use the bind method, which is essential when working with
events and jQuery.
59
Mostafa Bayomi mos.bayomi@gmail.com
60. THE BIND() METHOD
It will simply attach code to one or several events on a set of
elements.
$("a").bind("click", function() {
alert($(this).text());
});
It works by selecting all links (<a> elements) and then bind the
anonymous function you see to the click event.
60
Mostafa Bayomi mos.bayomi@gmail.com
61. THE BIND() METHOD(CONT’D)
When jQuery calls your method, it will pass information about the
event as the first parameter, if you have specified one or more
parameters on it.
For instance, the event object passed will contain information about
where the mouse cursor is, which type the event is, which keyboard
key or mouse button was pressed (if any) and much more.
$("#divArea").bind("mousemove", function(event)
{
$(this).text(event.pageX + "," + event.pageY);
});
61
Mostafa Bayomi mos.bayomi@gmail.com
62. THE BIND() METHOD(CONT’D)
The bind() method also allows you to pass in data of your own and
access it from the event object.
This also allows you to set values at the time you bind the event,
and be able to read this value at the time the event is invoked, even
though the original variable you used may have changed.
var msg = "Changed msg";
$("a").bind("click", { message : msg }, function(event) {
alert(event.data.message);
});
We pass the value as the secondary parameter of the bind() method,
as a map of keys and values. You can pass more than one value by
separating them with a comma. To access the value inside the event
62
handler, we use the data property of the event object. This property
contains sub-properties for each of the values you have passed
Mostafa Bayomi mos.bayomi@gmail.com
63. THE UNBIND() METHOD
we used the bind() method to subscribe to events with jQuery.
However.
You may need to remove these subscriptions again for various
reasons, to prevent the event handler to be executed once the event
occurs.
We do this with the unbind() method, which in its simplest form.
$("a").unbind();
This will remove any event handlers that you have attached with
the bind() function.
63
Mostafa Bayomi mos.bayomi@gmail.com
64. THE UNBIND() METHOD(CONT’D)
However, you may want to only remove event subscriptions of a
specific type, for instance clicks and doubleclicks:
$("a").unbind("click doubleclick");
Simply separate the event types with a space.
Note:
You can unbind events even if it were not added with the bind
function
64
Mostafa Bayomi mos.bayomi@gmail.com
65. THE UNBIND() METHOD(CONT’D)
jQuery allows you to subscribe to the same event type more than
one time.
This can come in handy if you want the same event to do more than
one thing in different situations.
You do it by calling the bind() method for each time you want to
attach a piece of code to it.
$("a").bind("click", function() {
alert("First event handler!");
});
$("a").bind("click", function() {
alert("Second event handler!");
65
$("a").unbind("click");
});
Mostafa Bayomi mos.bayomi@gmail.com
66. THE UNBIND() METHOD(CONT’D)
jQuery allows you to specify a secondary argument, which contains
a reference to the specific handler you would like to remove.
This way, we can make sure that we only remove the event
subscription we intend to.
var handler1 = function(){
alert("First event handler!");}
var handler2 = function() {
alert("Second event handler!");}
$("a").bind("click", handler1);
$("a").bind("click", handler2);
// remove one of the two handlers
66
$("a").unbind("click", handler2);
Mostafa Bayomi mos.bayomi@gmail.com
67. JQUERY EVENT DELEGATE() METH
OD
The delegate() method attaches one or more event handlers for specified
elements that are children of selected elements, and specifies a function to
run when the events occur.
Event handlers attached using the delegate() method will work for both
current and FUTURE elements (like a new element created by a script).
Ex:
$("div").delegate("button","click",function(){
$("p").slideToggle();
});
67
Mostafa Bayomi mos.bayomi@gmail.com
68. THE DATA() METHOD
Store arbitrary data associated with the matched elements.
It allows us to attach data of any type to DOM elements.
$('body').data('foo', 52);
$('body').data('bar', { myType: 'test', count: 40 });
$('body').data('foo'); // 52
$('body').data(); //{foo: 52, bar: { myType: 'test',count: 40 }}
68
Mostafa Bayomi mos.bayomi@gmail.com
69. ADD YOUR FUNCTIONS
You can add your plug-in to jQuery.
There are 2 basic objects that we will extend:
jQuery: mainly handles the internal processing.
jQuery.fn: handles the interaction of elements.
So if We want to create a general function like
$.post we must use jQuery object.
But if We need to create a new kind of animation
for our elements, using the power of the jQuery
selectors (for DOM’s elements) we would extend the
jQuery.fn object. 69
Mostafa Bayomi mos.bayomi@gmail.com
70. ADD YOUR FUNCTIONS(CONT’D)
We will create a plugin called inputHighlight in
jquery.inputHighlight.js file. Our plugin as you
may suppose will highlight our inputs when They
got the focus, changing their background color to
be more visible.
See Example
70
Mostafa Bayomi mos.bayomi@gmail.com
71. JQUERYUI
jQuery UI provides abstractions for low-level
interaction and animation, advanced effects and high-
level, themeable widgets, built on top of the jQuery
JavaScript Library, that you can use to build highly
interactive web applications.
jQuery UI provides a comprehensive set of core
interaction plugins, UI widgets and visual effects that
use a jQuery-style, event-driven architecture and a
focus on web standards, accessiblity, flexible styling,
and user-friendly design. All plugins are tested for
compatibility in IE 6.0+, Firefox 3+, Safari 3.1+, Opera
9.6+, and Google Chrome. 71
Mostafa Bayomi mos.bayomi@gmail.com
72. JQUERYUI(CONT’D)
Interactions:
Complex behaviors like drag and drop, resizing, selection
and sorting.
Enable draggable functionality on any DOM element.
Move the draggable object by clicking on it with the
mouse and dragging it anywhere within the viewport.
$("#draggable").draggable();
72
Mostafa Bayomi mos.bayomi@gmail.com
73. JQUERYUI(CONT’D)
Droppable:
Enable any DOM element to be droppable, a target for
draggable elements.
Demo
Resizable:
Enable any DOM element to be resizable. With the cursor
grab the right or bottom border and drag to the desired
width or height.
Demo
73
Mostafa Bayomi mos.bayomi@gmail.com
74. JQUERYUI(CONT’D)
Selectable:
Enable a DOM element (or group of elements) to be
selectable. Draw a box with your cursor to select items. Hold
down the Ctrl key to make multiple non-adjacent selections.
DEMO
Sortable:
Enable a group of DOM elements to be sortable. Click on
and drag an element to a new spot within the list, and the
other items will adjust to fit. By default, sortable items
sharedraggable properties. Demo
74
Mostafa Bayomi mos.bayomi@gmail.com
76. OTHER LIBRARIES
There are many and many libraries like jquery.
You can download it and by reading its docuentation
you can start scripting with it.
Mootools:
http://mootools.net/
Script.aculo.us:
http://script.aculo.us/
YUI:
http://developer.yahoo.com/yui/
76
Mostafa Bayomi mos.bayomi@gmail.com
Query is a JavaScript framework, which purpose is to make it much easier to use JavaScript on your website. You could also describe jQuery as an abstraction layer, since it takes a lot of the functionality that you would have to write many lines of JavaScript to accomplish and wraps it into functions that you can call with a single line of code. It's important to note that jQuery does not replace JavaScript, and while it does offer some syntactical shortcuts, the code you write when you use jQuery is still JavaScript code.
It uses the ID attribute of a HTML tag to locate the desired element. An ID should be unique, so you should only use this selector when you wish to locate a single, unique element. To locate an element with a specific ID, write a hash character, followed by the ID of the element you wish to locate
Elements with a specific class can be matched by writing a . character followed by the name of the class.
The selector simply tells jQuery to find all links (the a elements) which has a target attribute that equals the string value &quot;_blank&quot; and then replace the text to be &quot;new window&quot; on them.
EX: <div id=&quot;divTestArea1&quot;> <b>Bold text</b> <i>Italic text</i> <div id=&quot;divTestArea2&quot;> <b>Bold text 2</b> <i>Italic text 2</i> <div> <b>Bold text 3</b> </div> </div> </div> <script type=&quot;text/javascript&quot;> $(&quot;#divTestArea1 > b&quot;).css(&quot;color&quot;, &quot;blue&quot;); </script> As you will see, only the first bold tag is colored. Now, if you had used the second approach, all bold tags would have been colored blue.