JQuery
lightweight, "write less, do more", JavaScript library. Common tasks that require many lines of JS are wrapped into methods that are called with a single line:
HTML/DOM manipulation
CSS manipulation
HTML event methods
Effects and animations
AJAX
Utilities
Adding JQuery to a project
Download the jQuery library from jQuery.com
Include jQuery from a Google CDN. This will lead to faster load time.
JQuery Syntax
$(selector).action( )
$ - define/access jQuery
(selector) - uses CSS syntax to select elements. ("#id"), (".class") ("tag")
action( ) - to be performed on the element(s)
JQuery Selectors
$("*") - selects all elements
$(this) - selects the current HTML element
$("p.intro") - selects all
with class="intro"
$("p.first") - selects first
element
$("ul li:first") - Selects the first
element of the first
$("[attribute]") - selects all elements with a attribute
$("p[target='_blank']") - selects all
with a specified target value
$("tr:even") - Selects all even elements
$("tr:odd") - Selects all odd elements
JQuery EventsThe term "fires/fired" is often used with events. ie. "The keypress event is fired, the moment you press a key". ie:
Mouse Events:
click - when the user clicks on the HTML element
dblclick - when the user double-clicks on the HTML element
mouseenter - when the cursor enters [hover over] the HTML element
mouseleave - when the cursor leaves [hover out] the HTML element
hover - combo of mouse-enter & mouse-leave. Requires 2 functions.
Keyboard Events:
keypress - when a keypress event occurs.
keydown - when the key is pressed down.
keyup - when the key is released.
Form Events:
submit - when a form is submitted (press of submit button)
change - when the value of an element has been changed (only for , , )
focus - when the form field gets focus (input field is clicked on)
blur - when the form field loses focus
Document/Window Events:
load - deprecated and removed. There's also an AJAX method named load().
resize - when the browser window changes size.
scroll - when the user scrolls in the specified element.
unload - deprecated and removed.
The on() Method - multiple eventsattaches one or more event handlers for the selected elements
The Document Ready EventMost people put all jQuery methods inside a document ready event to prevent any jQuery code from running before the document is finished loading (is ready).
JQuery EffectsHide and Showyou can hide and show HTML elements with the
hide()
andshow()
methods.
Fadeyou can fade elements in&out of visibility. All of the below methods have an optional speed parameter as explained above.
fadeIn( [speed] ) - used to fade in a hidden element.
fadeOut( [speed] ) - used to fade out a hidden element.
fadeToggle( [speed] ) - toggles b/n fadeIn and fadeOut. If elements are faded out, fadeToggle will fade them in. vice verca.
fadeTo( [speed], opacity ) - allows fading to a given opacity (0 < x < 1 opaque)
Slidingslide elements up and down
slideDown( [speed] ) - used to slide down an element
slideUp( [speed] ) - used to slide up an element
slideToggle( [speed] ) - toggles b/n slideDown and slideUp. If elements have been slid down, slideToggle will slide them up. vice verca.
Animation - skipped, and the stop() method which stops animations.JQuery Callback FunctionsAll of the above event functions also have a second 'callback function' parameter, which is basically a function which is executed/called after the current effect is finished.
With effects, the next line can be run even though the effect is not finished. This can create errors. To prevent this, use a callback function. A callback function is executed after the current effect is finished.
JQuery Chainingyou can chain together actions/methods. Chaining allows us to run multiple jQuery methods (on the same element) within a single statement. Basically method chaining.
ie. chain together css() ,slideUp(), slideDown() : the element first changes to red, then slides up, then slides down:
jQuery DOM ManipulationJQuery has methods for changing and manipulating HTML elements and attributes.
JQuery GetGet Contentelement.text() - sets/returns inner text of selected element.
element.html() - sets/returns inner html of selected element.
element.val()- sets/returns the value from form fields.
Get Attributeselement.attr("attributeName") - gets the value of an attribute.
JQuery SetSet ContentSet AttributesJQuery AddWith JQuery, it's easy to add new elements/content.
Add New HTML Content.append()
- Inserts at the end of the selected elements.prepend()
- Inserts at the beginning of the selected elements.after()
- Inserts after the selected elements.before()
- Inserts before the selected elements
Adding Multiple ElementsAll 4 methods can take an infinite number of new elements as parameters:
JQuery Remove.remove( [selector] )
- removes the selected element(s) and its child elements.empty()
- removes the child elements of the selected element(s).
JQuery CSS ClassesWith jQuery, it is easy to manipulate the style of elements
jQuery Manipulating CSSaddClass()
- Adds 1 or more classes to the selected elements' attributes.removeClass()
- removes a specific class attribute from elemnt(s)toggleClass()
- adds a class if an element doesn't have it, removes a class if it does have it.
JQuery css()sets/returns 1 or more style properties for selected element(s).
Return a CSS property.css("propertyName")
- returns the value of the css property specified
Set a CSS propertycss("propertyName", "value")
- sets the value of the css property specifiedSetting multiple properties:
JQuery Dimensions.width()
- sets/returns the width of the element (excl. padding/border/margin).height()
- sets/returns the height of the element (excl. padding/border/margin).innerWidth()
- returns the width of an element (including padding).innerHeight()
- returns the height of an element (including padding).outerWidth()
- returns the width of an element (includes padding+border)..outerHeight()
- returns the height of an element (includes padding+border)..outerWidth(true)
- returns the width of an element (includes padding, border, margin)..outerHeight(true)
- returns the height of an element (includes padding, border, margin).
Misc:
$(document).width/height()
returns the width/height of the document.$(window).width/height()
returns the width/height of the window.
JQuery AJAXAJAX = Asynchronous JavaScript and XML.
AJAX is about loading data in the background and displaying it on the webpage, without reloading the whole page.
With the jQuery AJAX methods, you can request text, HTML, XML, or JSON from a remote server using both HTTP Get and HTTP Post - And you can load the external data directly into the selected HTML elements of your web page!
JQuery load()rrrloads data from a server and puts the returned data into the selected element
$(selector).load(URL, [data], [callback]);
URL - URL you wish to load.
data - optional parameter specifies a set of querystring key/value pairs to send along with the request.
callback - callback function. The callback has 3 parameters:
responseTxt
- contains the resulting content if the call succeedsstatusTxt
- contains the status of the call ('success'/'error')xhr
- contains the XMLHttpRequest object
get() and post()Two commonly used methods for a request-response between a client and server are: GET and POST:
GET - Requests data from a specified resource
POST - Submits data to be processed to a specified resource (can also act as GET)
$.get(URL, [callback])
- requests data from the server with an HTTP GET request.URL - URL you wish to request.
callback - optional callback function.
$.post(URL, data, [callback])
- requests data from the server using an HTTP POST request.URL - URL you wish to request.
data - optional parameter is some data to send along with the request.
callback - optional callback function.
JQuery noConflict()jQuery uses the
$
sign as a shortcut for jQuery.What if you want to use another JavaScript framework along with JQuery. What if those frameworks also use the $ sign as a shortcut? One of the frameworks' shortcut might stop working.
The
noConflict()
method releases the hold on the $ shortcut identifier, so that other scripts can use it.You can of course still use "jQuery", simply by writing the full name instead of the shortcut:
Custom shortcut for $You can also create your own shortcut very easily:
JQuery FiltersUse jQuery to filter/search for specific elements.
Filter TablesPerform a case-insensitive search for items in a table:
JQuery Traversing DOM TreeAncestorsAn ancestor is a parent, grandparent, great-grandparent, and so on.
parent()
- returns the direct parent element of the selected element.
Last updated