jQuery Intro
jQuery is a lightweight,”write less, do more”, JavaScript Library.
jQuery greatly simplifies JavaScript programming.
jQuery takes a lot of common tasks thatrequire many lines of JavaScript code to accomplish,
and wraps them into methods thatyou can call with a single line of code.
The jQuery library contains the following feature:
- HTML/DOM manipulations
- CSS manipulations
- HTML event methods
- Effects and animations
- AJAX
- Utilities
jQuery Start
Adding jQuery to web pages
There are several ways to start using jQuery on your web site:
- Download the jQuery library from jQuery.com
- Include jQuery from a CDN,like Google.
jQuery CDN
If you don’t want to download and host jQuery yourself,
you can include it from a CDN(Content Delivery Network).
Google Hosted Libraries
1 | <head> |
jQuery Syntax
The jQuery syntax is tailor-made for selecting HTML elements,
and performing some action on the elements.
$(selector).action
- A
$sign to define/access jQuery. - A
(selector)to “query”(or find) HTML elements. - A jQuery action() to be performed on the element(s).
jQuery - Get and Set Content and Attributes
One very important part of jQuery is the possibility to manipulate the DOM.
DOM = Document Object Model
The DOM defines a standard for accessing HTML and XML documents.
Get Content - text(),html(),and val()
Three simple,but useful,jQuery methods for DOM manipulation are:
text()-Sets or returns the text content of selected elements.html()-Sets or returns the text content of selected elements(including HTML markup).val()-Sets or returns the value of form fields.
Example
1 | //get the content of the div element. |
Difference between attr() and prop()
Both are used to get attribute values.
Boolean attributes such ascheckedonly set the default or initial value.
The most common boolean attributes arechecked,selected,disabled, andreadOnly
- doc
- The
prop()method should be used forbooleanattributes/properties and forproperties which don't exist in html( such as window.location). All other attributes (ones you can see)can and should continue to be manipulated with theattr()method.
Example
1 |
|
Get and Set CSS Classes
jQuery has several methods for CSS manipulation.
addClass()-Adds one or more classes to the selected elements.removeClass()-Removes one or more classes from the selected elements.toggleClass()-Toggles between adding/removing classes from the selected elements.css()-Sets or returns the style attributes.
Example
1 |
|
Return a CSS Property.
To return the value of a CSS property,use the following syntax
css("propertyName")
To set the value of a css property,use the following syntaxcss("propertyName","value")