Client-side development 1 - jQuery
Let’s discuss about jQuery is a framework or a library?
The very definition of
library and framework in JavaScript is quite inseparable.
By definition, a library is one which helps you write code faster and prabably better without affecting your coding stye or adding effects.
On the ther hand, a framework which helps you write large portion of HTML or actions with small amount of coding. It largely affects your coding pattern.Now consider jQuery, it can be library as it's mostly assist your coding without affecting. Or it can be framework as it allows you to write small set of codes to achieve likes of animations, UI toggles, etc.
By definition, a library is one which helps you write code faster and prabably better without affecting your coding stye or adding effects.
On the ther hand, a framework which helps you write large portion of HTML or actions with small amount of coding. It largely affects your coding pattern.Now consider jQuery, it can be library as it's mostly assist your coding without affecting. Or it can be framework as it allows you to write small set of codes to achieve likes of animations, UI toggles, etc.
Now We going to see features provide
by jQuery
- Simple and easy
- Lightweight
- CSS manipulation
- Html manipulation
- Cross browser support
- Event handling
- JavaScript Library
- Ajax Support
- Built-in Animation
JQuery Feature and Explanation.
- Simple and easy: It have predefined method using you can perform any task easily compare to JavaScript. And it is easy to learn.
- Lightweight: It is very lightweight library - about 19KB in size ( Minified and gzipped ).
- CSS manipulation: It have predefined css() method for manipulate style for any Html elements.
- Html manipulation: The jQuery made it easy to select DOM elements, traverse them and modifying their content.
- Cross browser support: It support all modern web-browser including IE-6.
- Event handling: It support event handling like click mouse button.
- JavaScript Library: It is JavaScript library.
- Ajax Support: It support ajax, you can develop a responsive and feature-rich site using AJAX technology.
- Built-in Animation: It have predefined method "animate()" for create custom animation on web-page.
Advantage and Disadvantages of jQuery
The advantages of jQuery
The main advantage of jQuery is that it is much easier than its competitors. You can add plugins easily, translating this into a substantial saving of time and effort. In fact, one of the main reasons why Resig and his team created jQuery was to buy time (in the web development world, time matters a lot).The open source license of jQuery allows the library to always have constant and fast support, constantly publishing updates. The jQuery community is active and extremely hardworking.
Another advantage of jQuery over its competitors such as Flash and pure CSS is its excellent integration with AJAX.
The disadvantages of jQuery
One of the main
disadvantages of jQuery is the large number of published versions in the short
time. It does not matter if you are running the latest version of jQuery,
you will have to host the library yourself (and update it constantly), or
download the library from Google (attractive, but can bring incompatibility
problems with the code).
In addition to
the problem of the versions, other disadvantages that we can mention:
- jQuery is easy to install and learn, initially. But it’s not that easy if we compare it with CSS
- If jQuery is improperly implemented as a Framework, the development environment can get out of control.
jQuery Selectors
Selector
|
Example
|
Selects
|
$("*")
|
All elements
|
|
$("#lastname")
|
The element
with id="lastname"
|
|
$(".intro")
|
All elements
with class="intro"
|
|
$(".intro,.demo")
|
All elements
with the class "intro" or "demo"
|
|
$("p")
|
All <p>
elements
|
|
$("h1,div,p")
|
All <h1>,
<div> and <p> elements
|
|
$("p:first")
|
The first
<p> element
|
|
$("p:last")
|
The last
<p> element
|
|
$("tr:even")
|
All even
<tr> elements
|
|
$("tr:odd")
|
All odd
<tr> elements
|
|
$("p:first-child")
|
All <p> elements that are
the first child of their parent
|
|
$("p:first-of-type")
|
All <p> elements that are
the first <p> element of their parent
|
|
$("p:last-child")
|
All <p> elements that are
the last child of their parent
|
|
$("p:last-of-type")
|
All <p> elements that are
the last <p> element of their parent
|
|
$("p:nth-child(2)")
|
All <p> elements that are
the 2nd child of their parent
|
|
$("p:nth-last-child(2)")
|
All <p> elements that are
the 2nd child of their parent, counting from the last child
|
|
$("p:nth-of-type(2)")
|
All <p> elements that are
the 2nd <p> element of their parent
|
|
$("p:nth-last-of-type(2)")
|
All <p> elements that are
the 2nd <p> element of their parent, counting from the last child
|
|
$("p:only-child")
|
All <p> elements that are
the only child of their parent
|
|
$("p:only-of-type")
|
All <p> elements that are
the only child, of its type, of their parent
|
|
$("div > p")
|
All <p> elements that are a
direct child of a <div> element
|
|
$("div p")
|
All <p> elements that are
descendants of a <div> element
|
|
$("div + p")
|
The <p> element that are
next to each <div> elements
|
Let’s Tolk to benefits of using jQuery event handling Over HTML event
attributes list of event supported by jQuery
The majority of browser events bubble, or propagate, from the
deepest, innermost element (the event target) in the document
where they occur all the way up to the body and the document
element. In Internet Explorer 8 and lower, a few events such as change
and submit do not natively bubble but jQuery patches these to
bubble and create consistent cross-browser behavior.If
selector is omitted or is null, the event handler is referred
to as direct or directly-bound. The handler is called every time an event occurs on
the selected elements, whether it occurs directly on the element or bubbles
from a descendant (inner) element.When a
selector is provided, the
event handler is referred to as delegated. The handler is not called when the event occurs
directly on the bound element, but only for descendants (inner elements) that
match the selector. jQuery bubbles the event from the event target up to the
element where the handler is attached (i.e., innermost to outermost element)
and runs the handler for any elements along that path matching the selector.Event handlers are bound only to the currently selected elements; they must exist at the time your code makes the call to
.on(). To ensure the elements are present and can be
selected, place scripts after the elements in the HTML markup or perform event
binding inside a document ready handler. Alternatively, use delegated events to
attach event handlers.Delegated event handlers have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or
document
if the event handler wants to monitor all bubbling events in the document. The document
element is available in the head of the document before loading any other HTML, so it
is safe to attach events there without waiting for the document to be ready.In addition to their ability to handle events on descendant elements not yet created, another advantage of delegated events is their potential for much lower overhead when many elements must be monitored. On a data table with 1,000 rows in its
tbody,
this example attaches a handler to 1,000 elements
jQuery Event Methods
Event methods trigger or attach a function to an event
handler for the selected elements.
The following table lists all the jQuery methods used to
handle events.
Method / Property
|
Description
|
Deprecated in version 3.0. Use the
on() method
instead. Attaches event handlers to elements
|
|
Attaches/Triggers the blur event
|
|
Attaches/Triggers the change event
|
|
Attaches/Triggers the click event
|
|
Attaches/Triggers the double click
event
|
|
Deprecated in version 3.0. Use the
on() method
instead. Attaches a handler to current, or future, specified child elements
of the matching elements
|
|
Removed in version 1.9. Removes
all event handlers added with the live() method
|
|
Removed in version 3.0.
Attaches/Triggers the error event
|
|
The current DOM element within the
event bubbling phase
|
|
Contains the optional data passed
to an event method when the current executing handler is bound
|
|
Returns the element where the
currently-called jQuery event handler was attached
|
|
Returns whether
event.preventDefault() was called for the event object
|
|
Returns whether
event.stopImmediatePropagation() was called for the event object
|
|
Returns whether
event.stopPropagation() was called for the event object
|
|
Returns the namespace specified
when the event was triggered
|
|
Returns the mouse position
relative to the left edge of the document
|
|
Returns the mouse position
relative to the top edge of the document
|
|
Prevents the default action of the
event
|
|
Returns which element being
entered or exited on mouse movement
|
|
Contains the last/previous value
returned by an event handler triggered by the specified event
|
|
Prevents other event handlers from
being called
|
|
Prevents the event from bubbling
up the DOM tree, preventing any parent handlers from being notified of the
event
|
|
Returns which DOM element
triggered the event
|
|
Returns the number of milliseconds
since January 1, 1970, when the event is triggered
|
|
Returns which event type was
triggered
|
|
Returns which keyboard key or
mouse button was pressed for the event
|
|
Attaches/Triggers the focus event
|
|
Attaches an event handler to the
focusin event
|
|
Attaches an event handler to the
focusout event
|
|
Attaches two event handlers to the
hover event
|
|
Attaches/Triggers the keydown
event
|
|
Attaches/Triggers the keypress
event
|
|
Attaches/Triggers the keyup event
|
|
Removed in version 1.9. Adds one
or more event handlers to current, or future, selected elements
|
|
Removed in version 3.0. Attaches
an event handler to the load event
|
|
Attaches/Triggers the mousedown
event
|
|
Attaches/Triggers the mouseenter
event
|
|
Attaches/Triggers the mouseleave
event
|
|
Attaches/Triggers the mousemove
event
|
|
Attaches/Triggers the mouseout
event
|
|
Attaches/Triggers the mouseover
event
|
|
Attaches/Triggers the mouseup
event
|
|
Removes event handlers attached
with the on() method
|
|
Attaches event handlers to
elements
|
|
Adds one or more event handlers to
selected elements. This handler can only be triggered once per element
|
|
Takes an existing function and
returns a new one with a particular context
|
|
Specifies a function to execute
when the DOM is fully loaded
|
|
Attaches/Triggers the resize event
|
|
Attaches/Triggers the scroll event
|
|
Attaches/Triggers the select event
|
|
Attaches/Triggers the submit event
|
|
Removed in version 1.9. Attaches
two or more functions to toggle between for the click event
|
|
Triggers all events bound to the
selected elements
|
|
Triggers all functions bound to a
specified event for the selected elements
|
|
Deprecated in version 3.0. Use the
off() method
instead. Removes an added event handler from selected elements
|
|
Deprecated in version 3.0. Use the
off() method
instead. Removes an event handler to selected elements, now or in the future
|
|
Removed in version 3.0. Attaches
an event handler to the unload event
|
How to declare jQuery event handlers outside the
$(document).ready() function,
Is
it correct to create functions inside of
$(document).ready(function() {
like so :
$(document).ready(function() {
function callMe() {
}
});
The function
inside of the .ready() does not have to call before dom is ready and event
inside of the ready() is triggered.
Just
to clarify a little bit - here's the code which would illustrate the problem:
$(function() {
var
ind = 0;
//
some event is executed and changes the value of the ind
//
another event which affects the ind variable
//
and another one - after this event we call our function
jQuery advanced features
1) jQuery Objects as Arrays
The result of running a selector is a jQuery object. However, the library makes it appear as if you are working with an array by defining index elements and a length.// Selecting all the navigation buttons:
var buttons = $('#navigation a.button');
// We can loop though the collection:
for(var i=0;i<buttons.length;i++){
console.log(buttons[i]); // A DOM element, not a jQuery object
}
// We can even slice it:
var firstFour = buttons.slice(0,4);
If
performance is what you are after, using a simple for
(or a while) loop instead
of $.each(), can make
your code several
times faster.Checking the length is also the only way to determine whether your collection contains any elements.
if(buttons){ // This is always true
// Do something
}
if(buttons.length){ // True only if buttons contains elements
// Do something
}
2) The Selector Property
jQuery provides a property which contains the selector that was used to start the chain.$('#container li:first-child').selector // #container li:first-child
$('#container li').filter(':first-child').selector // #container li.filter(:first-child)
Although
the examples above target the same element, the selectors are quite different.
The second one is actually invalid - you can't use it as the basis of a new
jQuery object. It only shows that the filter method was used to narrow down the
collection.3) Create an Empty jQuery Object
Creating a new jQuery object can bring significant overhead. Sometimes, you might need to create an empty object, and fill it in with the add() method later.var container = $([]);
container.add(another_element);
This
is also the basis for the quickEach() method that you can use as a faster alternative
to the default each().4) Select a Random Element
As I mentioned above, jQuery adds its own selection filters. As with everything else in the library, you can also create your own. To do this simply add a new function to the$.expr[':']
object. One awesome use case was presented by Waldek Mastykarz on his blog:
creating a selector for retrieving a random element. You can see a slightly
modified version of his code below:(function($){
var random = 0;
$.expr[':'].random = function(a, i, m, r) {
if (i == 0) {
random = Math.floor(Math.random() * r.length);
}
return i == random;
};
})(jQuery);
// This is how you use it:
$('li:random').addClass('glow');
5) Use CSS Hooks
The CSS hooks API was introduced to give developers the ability to get and set particular CSS values. Using it, you can hide browser specific implementations and expose a unified interface for accessing particular properties.$.cssHooks['borderRadius'] = {
get: function(elem, computed, extra){
// Depending on the browser, read the value of
// -moz-border-radius, -webkit-border-radius or border-radius
},
set: function(elem, value){
// Set the appropriate CSS3 property
}
};
// Use it without worrying which property the browser actually understands:
$('#rect').css('borderRadius',5);
What
is even better, is that people have already built a rich library
of supported CSS hooks that you can use for free in your next project.6) Use Custom Easing Functions
You have probably heard of the jQuery easing plugin by now - it allows you to add effects to your animations. The only shortcoming is that this is another JavaScript file your visitors have to load. Luckily enough, you can simply copy the effect you need from the plugin file, and add it to thejQuery.easing object:$.easing.easeInOutQuad = function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t + b;
return -c/2 * ((--t)*(t-2) - 1) + b;
};
// To use it:
$('#elem').animate({width:200},'slow','easeInOutQuad');
7) The $.proxy()
One of the drawbacks to using callback functions in jQuery has always been that when they are executed by a method of the library, the context is set to a different element. For example, if you have this markup:<div id="panel" style="display:none">
<button>Close</button>
</div>
And
you try to execute this code:$('#panel').fadeIn(function(){
// this points to #panel
$('#panel button').click(function(){
// this points to the button
$(this).fadeOut();
});
});
You
will run into a problem - the button will disappear, not the panel. With $.proxy, you can write it like this:$('#panel').fadeIn(function(){
// Using $.proxy to bind this:
$('#panel button').click($.proxy(function(){
// this points to #panel
$(this).fadeOut();
},this));
});
Which
will do what you expect. The $.proxy
function takes two arguments - your original function, and a context. It
returns a new function in which the value of this is always fixed to the context.
You can read more about.
Comments
Post a Comment