jQuery
jQuery is a fast, small, and feature-rich JavaScript library. It
makes things like HTML document traversal and manipulation, event
handling, and animation much simpler with an easy-to-use API that
works across a multitude of browsers. With a combination of
versatility and extensibility, jQuery has changed the way that
millions of people write JavaScript.
The jQuery library contains the following features:
- HTML/DOM manipulation
- CSS manipulation
- HTML event methods
- Effects and animations
- AJAX
- Utilities
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 (Content Delivery Network), like Google
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
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 jQuery action() to be performed on the element(s)
JavaScript
$(document).ready(function () {
$("#button").click(function () {
$("#p").hide();
});
});
<button id="button" type="button">Hide Text</button>
<p id="p"> This text will disapear when you click on the button.</p>
Result
This text will disapear when you click on the button.
It is possible to use jQuery function instead of the $ sign.
The following example does the same as the example above.
JavaScript
jQuery(document).ready(function () {
jQuery("#button").click(function () {
jQuery("#p").hide();
});
});
Result
This text will disapear when you click on the button.
To avoiding Library conflicts with other JavaScript libraries, jQuery
provides a noConflict() method.
This method releases the hold on the $ shortcut identifier, so that
other scripts can use it.
You can use the jQuery name directly in place of $, as shown in the
following example:
JavaScript
$(document).ready(function () {
$("#button102").click(function () {
jq = $.noConflict();
jq("#p102").hide();
});
jq("#button103").click(function () {
$ = jq.noConflict();
alert("Off");
});
});
Result
This text will disapear when you click on the button.
jQuery Document Ready
The document ready event occurs when the HTML document has been
loaded and the DOM is ready, even if all the images have not loaded
yet.
The document ready event is a jQuery event that occurs when the DOM
is fully loaded.
This event is already explained in the jQuery Syntax chapter.
$(document).ready(function(){
// jQuery methods go here...
});
// OR
$(function()
{
// Your code goes here
})
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 name, id, classes, types, attributes, values of attributes,
and much more. It's based on the existing CSS Selectors, and in
addition, it has some custom selectors.
All selectors in jQuery start with the dollar sign and parentheses:
$().
The jQuery element selector selects elements based on the element
name.
The jQuery #id selector uses the id attribute of an HTML tag to find
the specific element.
The jQuery .class selector finds elements with a specific class.
JavaScript
<button id="button81" type="button">ID btn</button>
<button class="button82" type="button">Class Btn</button>
$(document).ready(function(){
$("#button81").click(function(){
alert("ID Button Clicked");
});
$(".button82").click(function(){
alert("Class Button Clicked");
});
});
Result
jQuery objects (created with either the $ or jQuery methods) are not the same as JavaScript objects created with getElementById. In plain JavaScript, you can use a statement like object = document.getElementById('result') followed by (for example) object.innerHTML = 'something'. But in the preceding example, $('#result').innerHTML would not work, because innerHTML is not a property of a jQuery object.
CSS Method
It takes two arguments, the property name to be accessed and a value to be applied.
You can also use the css method to return (rather than set) a computed value by supplying only a property name
(and no second argument).
Remember that the value returned is the computed value. In other words, jQuery will compute and return the
value as used by the browser at the moment the method is called.
This computed value, though, will always be in a form that can be assigned back to the element (or any other
element) via the second argument of the css method.
JavaScript
<button id="button11" type="button">Click Me</button>
<p id="p11">This text will change color and slide up and down when you click on the button.</p>
$(document).ready(function(){
$("#button11").click(function(){
$("#p11").css("color", "red");
color = $("#p11").css("color");
alert(color);
});
});
Result
This text will change color and slide up and down when you click on the button.
jQuery Events
jQuery events are actions that can be detected by your web page. Any
event that happens in the browser can be detected and used to run
JavaScript code.
Here are some examples of jQuery events:
- Mouse events
- Keyboard events
- Form events
- Document/Window events
- Event methods
JavaScript
$(document).ready(function(){
$("#button112").click(function(){
$("#p112").hide();
});
$("#button113").click(function(){
$("#p112").show();
});
});
<button id="button112" type="button">Hide</button>
<button id="button113" type="button">Show</button>
<p id="p112">This text will disapear when you click on the button.</p>
Result
This text will disapear when you click on the button.
The following table lists the most important jQuery methods for event handling:
Method | Description |
---|---|
click() | Triggers the click event |
dblclick() | Triggers the dblclick event |
mouseenter() | Triggers the mouseenter event |
mouseleave() | Triggers the mouseleave event |
mousedown() | Triggers the mousedown event |
mouseup() | Triggers the mouseup event |
hover() | Triggers the mouseenter and mouseleave events |
focus() | Triggers the focus event |
blur() | Triggers the blur event |
on() | Attaches one or more event handlers to the selected elements |
The complete list of jQuery event methods can be found on the jQuery API documentation page.
jQuery Effects
jQuery comes with various effects methods that can be used to create
animations easily on your web page.
The following table lists all the jQuery methods for creating
animation effects:
Method | Description |
---|---|
hide() | Hides the selected elements |
show() | Shows the selected elements |
toggle() | Toggles between hide() and show() for the selected elements |
fadeIn() | Fades in the selected elements |
fadeOut() | Fades out the selected elements |
fadeToggle() | Toggles between fadeIn() and fadeOut() for the selected elements |
slideDown() | Slides down the selected elements |
slideUp() | Slides up the selected elements |
slideToggle() | Toggles between slideDown() and slideUp() for the selected elements |
JavaScript
$(document).ready(function(){
$("#button114").click(function(){
$("#p114").slideUp();
});
$("#button115").click(function(){
$("#p114").slideDown();
});
});
<button id="button114" type="button">Slide Up</button>
<button id="button115" type="button">Slide Down</button>
<p id="p114">This text will slide up and down when you click on the button.</p>
Result
This text will slide up and down when you click on the button.
The jQuery animate() method is used to create custom animations.
The following example demonstrates the animate() method. It animates a div element.
The div element gradually changes from width: 250px to width: 500px, and from height: 500px to height: 1000px.
JavaScript
$(document).ready(function(){
$("#button116").click(function(){
$("#div116").animate({
width: "200px",
height: "200px"
});
});
});
<button id="button116" type="button">Animate </button>
<div id="div116" style="background-color:lightblue;height:100px;width:100px;">
Result
The complete list of jQuery effects methods can be found on the jQuery API documentation page.
jQuery AJAX
jQuery AJAX methods allow you to send and retrieve data from the
server without reloading the entire page.
The following table lists the most important methods for AJAX:
Method | Description |
---|---|
$.ajax() | Performs an async AJAX request |
$.get() | Loads data from the server using a HTTP GET request |
$.post() | Loads data from the server using a HTTP POST request |
$.getJSON() | Loads JSON-encoded data from the server using a HTTP GET request |
$.ajax({
url: "demo_test.txt",
success: function(result){
$("#div1").html(result);
}
});
jQuery load() Method
The jQuery load() method is a simple, but powerful AJAX method. The
load() method loads data from a server and puts the returned data
into the selected element.
The load() method loads data from the server and places the returned
HTML into the matched element. This method provides a simple way to
load data asynchronous from a web server.
The syntax for the load() method is:
$(selector).load(URL,data,callback);
The required URL parameter specifies the URL you wish to load. The
optional data parameter specifies a set of querystring key/value
pairs to send along with the request. The optional callback
parameter is the name of a function to be executed after the load()
method is completed.
JavaScript
$(document).ready(function(){
$("#button2").click(function(){
$("#div2").load("demo_test.txt");
});});
Result
The previous example loads the content of the file "demo_test.txt"
into a specific <div> element with id="div2" after clicking on "Test" button
It is also possible to add a jQuery selector to the URL parameter:
JavaScript
$(document).ready(function () {
$("#button3").click(function () {
$("#div3").load("index.html #Course_Objectives");
});
});
Result
The previous example loads the content of the element with id="Course_Objectives" from the file "index.html"
into a specific <div> element with id="div3" after clicking on "Test" button
In the next example, we will do the same thing and a callback function will be executed after the load()
method is completed:
JavaScript
$(document).ready(function () {
$("#button4").click(function () {
$("#div4").load("index.html #Course_Objectives", function (responseTxt, statusTxt, xhr) {
if (statusTxt == "success")
alert("External content loaded successfully!");
if (statusTxt == "error")
alert("Error: " + xhr.status + ": " + xhr.statusText);
});
});
});
Result
The previous example loads the content of the element with id="Course_Objectives" from the file "index.html"
into a specific <div> element with id="div4" after clicking on "Test" button
A callback function will be executed after the load() method is completed. The function will display a
message
according to the status of the load() method.
The callback function can have different parameters:
- responseTxt - contains the resulting content if the call succeeds
- statusTxt - contains the status of the call
- xhr - contains the XMLHttpRequest object
jQuery - AJAX get() and post() Methods
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
The following example uses the $.get() method to retrieve data from a file on the server:
JavaScript
$(document).ready(function(){
$("#button10").click(function(){
$.get("demo_test.txt", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
Result
The previous example uses the $.get() method to retrieve data from a file on the server.
The function(data, status) specifies a callback function to be run when the $.get() method is successful.
The
function(data, status) parameters specify the data returned from the server and the status of the call.