Module 7 - Introduction to jQuery: CS 112 : Javascript Prog - Minassian... https://ilearn.laccd.edu/courses/283068/pages/module-7-introduction-to...
Module 7 - Introduc�on to jQuery
1. What is jQuery?
jQuery is a JavaScript library used to simplify writing JavaScript code. jQuery is simply a
JavaScript wrapper. In other words, it encapsulates JavaScript and provides you with more feature
rich functionality right out of the box. jQuery also has a very large selection of third-party plugins
that you can include in your project and use right away. It's currently the most widely adopted
JavaScript framework out there. Finally, jQuery is based on Selectors and Actions. Selectors are
the method used to retrieve DOM elements to perform some action on. jQuery as the name
implies, has a very powerful query methods giving you the ability to retrieve DOM elements with
ease without having to write multiple lines of JavaScript to do the equivalent.
2. Including jQuery in Your Project
You have two methods of including the jQuery framework in your project.
1. Download the jQuery library from https://jquery.com/download/#jquery (https://
jquery.com/download/#jquery) (Use the compressed production version)
2. Use a CDN (Content Delivery Network) version in your project which is hosted by a third party.
You can copy/paste the script tag to a CDN by going to https://code.jquery.com/ (https://
code.jquery.com/) (Use the minified version)
For example, the latest version of jQuery can be included in your project by copy/pasting the
following script source to the bottom of the <body> section of your project
<!DOCTYPE html>
<html>
<head><title>jQuery Example</title></head>
<body>
<!-- Your HTML Here -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
crossorigin="anonymous"></script>
<script>
// jQuery code goes here
</script>
</body>
</html>
1 of 12 11/14/2024, 12:59 PM
Module 7 - Introduction to jQuery: CS 112 : Javascript Prog - Minassian... https://ilearn.laccd.edu/courses/283068/pages/module-7-introduction-to...
3. jQuery Syntax
Like mentioned above, jQuery is heavily based on selectors and actions:
$("selector").action();
You reference jQuery by using the dollar-sign character $ followed by a String selector query in
parenthesis, followed by a dot then the action to perform on the elements returned by the selector.
An easy way to remember the jQuery syntax is to use the "Hey jQuery! Go get" phrase. The dollar
sign $ is the "Hey jQuery!" part and the selector in parenthesis (selector) is the "Go get" part.
4. Selectors
jQuery selectors allows you to search for HTML elements and manipulate them. There's extensive
ways to select elements in jQuery but we will cover the more common methods here:
a. Select by Element
You can select all elements on a page based on the element type using the name of the element.
For example, if we wanted to select all paragraph <p> elements, we can do:
<p>This is a paragraph</p>
<p>This is a second paragraph</p>
<script>
$("p").someAction(); // Selects both paragraphs from the HTML above.
</script>
b. Select by Element ID
Another useful method of selecting elements is by its id attribute. This allows you to select a
single element based on the id you assign. You begin the selector with the hash # character
followed by the id:
<p>This is a paragraph</p>
<input id="firstName" type="text"/>
<script>
$("#firstName").someAction(); // Selects the input with id 'firstName' above
</script>
c. Select by Class Name
2 of 12 11/14/2024, 12:59 PM
Module 7 - Introduction to jQuery: CS 112 : Javascript Prog - Minassian... https://ilearn.laccd.edu/courses/283068/pages/module-7-introduction-to...
Selecting elements by CSS class allows you to select multiple elements that are assigned a
specific class. You begin the selector by a period . followed by the class name:
<p>This is a paragraph</p>
<p class="lucky">This is a paragraph</p>
<input class="lucky" type="text"/>
<script>
$(".lucky").someAction(); // Selects the paragraph AND input that have class of 'lucky'
</script>
d. More jQuery Selectors
Syntax Description
$("*") Selects all elements
$(this) Selects the current HTML element
$("p.intro") Selects all <p> elements with class="intro"
$("p:first") Selects the first <p> element
$("ul li:first") Selects the first <li> element of the first <ul>
$("ul li:first-child") Selects the first <li> element of every <ul>
$("[href]") Selects all elements with an href attribute
$("a[target='_blank']") Selects all <a> elements with a target attribute value equal to "_blank"
Selects all <a> elements with a target attribute value NOT equal to
$("a[target!='_blank']")
"_blank"
$(":button") Selects all <button> elements and <input> elements of type="button"
$("tr:even") Selects all even <tr> elements
$("tr:odd") Selects all odd <tr> elements
An extensive list of selectors can be seen on w3schools (https://www.w3schools.com/jquery/
jquery_ref_selectors.asp) .
5. Events
An event on a web page is anything that you can trigger some block of code to run when that
event occurs. There are many events you can trigger one but some of the more common ones are
when you click a HTML element, hover your mouse over an element or say focus to an element.
3 of 12 11/14/2024, 12:59 PM
Module 7 - Introduction to jQuery: CS 112 : Javascript Prog - Minassian... https://ilearn.laccd.edu/courses/283068/pages/module-7-introduction-to...
a. Document Ready
It's a common practice to begin executing your JavaScript or jQuery code once the page has fully
loaded. This is due to the fact that we can't assume when the JavaScript in your page will begin
executing due to way each browser functions. Therefore, it's best practice to place your code in an
event that triggers when the page has fully loaded. In jQuery, we do this by encapsulating the
code in the ready event of the document element:
<script>
$(document).ready(function() {
// Code to run when page fully loads
});
</script>
The ready event fires when the page fully loads. This event takes in a reference to a function to
run. We can either specify a function we write ourselves or define one inline such as the example
above.
b. Defining Events
In jQuery, we define events by using the .on method on the selection. The .on method accepts an
event name as a string and the reference to the function to execute once that event fires. For
example, if we wanted to show an alert each time a paragraph element is clicked, we can write:
<script>
$("p").on("click", function() {
alert('Hello');
});
</script>
c. $(this) Selector
When we deal with selecting multiple elements to bind events to, we need a way of referencing
the actual element that the action is triggered for in our code. For example, if our goal was to
output the source of ANY image that is clicked on our page, we need to someone reference the
actual image that is clicked, but we only have a single function for the click event. To address this
issue, we can always reference the element the event is triggered for using the $(this)
selector. The example below shows how to output the source of ANY image that is clicked to the
console.
<img src="butterfly.png"/>
<img src="ant.png"/>
<img src="birds.png"/>
4 of 12 11/14/2024, 12:59 PM
Module 7 - Introduction to jQuery: CS 112 : Javascript Prog - Minassian... https://ilearn.laccd.edu/courses/283068/pages/module-7-introduction-to...
<script>
$("img").on("click", function() {
console.log($(this).attr("src"));
});
</script>
The value of $(this) inside the function will always dynamically equal the element that the event
is triggered for
d. Some Common Events
Mouse Events Keyboard Events Form Events Document/Window Events
click keypress submit load
dblclick keydown change resize
mouseenter keyup focus scroll
mouseleave blur unload
For an extensive list of events, refer to w3schools (https://www.w3schools.com/jquery/
jquery_ref_events.asp)
6. Effects
jQuery has many built-in methods for animating HTML elements. It's important to note that these
effects may hide elements but they are not permanently removed from the DOM. let's take a look
at a few examples:
a. Showing/Hiding Elements
You can quickly show or hide elements with jQuery by simply using the show(), hide() and
toggle() methods. show() and hide() are self-explanatory but the toggle() method is special in that
it detects whether an element is visible or not and performs the opposite action based on the
visibility of the element.
<script>
$("p").show(); // makes all paragraph elements visible if they are hidden
$("p").hide(); // hides all paragraph elements if they are visible
$("p").toggle(); // hides or shows all paragraph elements based on their current visibility
</script>
b. Fading/Sliding Elements
5 of 12 11/14/2024, 12:59 PM
Module 7 - Introduction to jQuery: CS 112 : Javascript Prog - Minassian... https://ilearn.laccd.edu/courses/283068/pages/module-7-introduction-to...
You can fade in/out elements using the fadeIn(), fadeOut(), fadeToggle() and fadeTo() methods.
fadeIn() and fadeOut() are self-explanatory but the fadeToggle() methods automatically fades in or
out based on the current state of the element. fadeTo() will fade an element to a specified opacity
between 0 and 1:
<script>
$("p").fadeIn(); // fades in all paragraph elements if they are in a hidden state
$("p").fadeOut(); // fades out all paragraph elements if they are in a visible state
$("p").fadeToggle(); // fades in or out all paragraph elements based on their current visibility st
ate
$("p").fadeTo(.5); // fades all paragraph elements to an opacity of 50%
</script>
You can also slide up/down elements using the slideDown(), slideUp() and slideToggle()
methods. slideUp() and slideDown() are self-explanatory but slideToggle() will slide up or down
automatically based on the state of the element.
<script>
$("p").slideUp(); // slides up all paragraph elements if they are in a visible state
$("p").slideDown(); // slides down all paragraph elements if they are in a hidden state
$("p").slideToggle(); // slides up or down all paragraph elements based on their current visibility
state
</script>
7. Callbacks & Chaining
Callbacks in jQuery or even JavaScript are anonymous functions that execute once the current
asynchronous method is completely finished. When jQuery begins executing a asynchronous
method, it does not wait until the method is complete before moving down to execute the code
that comes after the method. Therefore, it would be impossible to execute some code after such
method since there would be no way to determine when it's finished. Callback functions exist to
allow you to have control of what happens when such a method finishes. For example, the jQuery
slideUp() method takes a second or two to slide an element up. We can use a callback function on
the slideUp() method to detect this and take some action. For example:
$("p").slideUp(function() {
alert("The slideUp animation is complete!");
});
It's difficult to list all methods that accept a callback function but most-if-not-all asynchronous
methods do. You can refer to the jQuery documentation to find out if a method accepts a callback.
a. Chaining
6 of 12 11/14/2024, 12:59 PM
Module 7 - Introduction to jQuery: CS 112 : Javascript Prog - Minassian... https://ilearn.laccd.edu/courses/283068/pages/module-7-introduction-to...
jQuery allows you to chain methods to have them execute one after another without having to
query the same element multiple times. For example, if we wanted to execute the slideUp() and
slideDown() methods one after another, we can do:
$("p").slideUp().slideDown();
The equivalent to the above example would be:
$("p").slideUp();
$("p").slideDown();
8. Reading HTML Elements
jQuery makes it easy to read content from the DOM using built-in methods. It has several methods
for reading contents of HTML elements:
• text(), html(), val() and attr() respectively.
a. text()
text() returns any text inside the selected element excluding any HTML elements
<p>Hello <strong>World</strong></p>
<script>
$("p").text(); // returns "Hello World" without the <strong> tag
</script>
b. html()
html() returns all text and HTML inside the selected element.
<p>Hello <strong>World</strong></p>
<script>
$("p").html(); // returns "Hello <strong>World</strong>"
</script>
c. val()
val() is special in that it's used to read the entered value in form elements such as a text box
7 of 12 11/14/2024, 12:59 PM
Module 7 - Introduction to jQuery: CS 112 : Javascript Prog - Minassian... https://ilearn.laccd.edu/courses/283068/pages/module-7-introduction-to...
<input type="text" id="firstName/>
<script>
$("#firstName").val(); // returns value entered in the text box.
</script>
d. a�r()
attr("attribute") is used to get the value of a HTML attribute. For example. to get the href attribute
of a link:
<a href="http://www.google.com" id="g">Google</a>
<script>
$("#g").attr("href"); // returns "http://www.google.com"
</script>
9. Se�ng HTML Elements
jQuery makes it easy to modify the DOM using built-in methods. It has several methods for setting
HTML elements and their attributes:
• text(), html(), val() and attr() respectively.
a. text()
text("Text Content") can be used to set the text inside the selected element. Any HTML tags
entered in this method will be display literally.
<p></p>
<script>
$("p").text("Hello World!"); // Sets the text in the paragraph to "Hello World!"
</script>
b. html()
html("<p>HTML Content</p>") can be used to set the HTML and text inside the selected
element.
<p></p>
<script>
8 of 12 11/14/2024, 12:59 PM
Module 7 - Introduction to jQuery: CS 112 : Javascript Prog - Minassian... https://ilearn.laccd.edu/courses/283068/pages/module-7-introduction-to...
$("p").html("Hello <strong>World</strong>"); // Sets the HTML in the paragraph to "Hello World" (bo
ld "World")
</script>
c. val()
val("Form Content") can be used to set the value of a text box
<input type="text" id="firstName/>
<script>
$("#firstName").val("Nick"); // sets the text in the text box to "Nick".
</script>
d. a�r()
attr() can be used to s used to add/modify an attribute of the selected elements.:
<a id="g">Google</a>
<script>
$("#g").attr("href", "http://www.google.com"); // sets the href attribute of the link to "http://ww
w.google.com"
</script>
10. Crea�ng HTML Elements
jQuery makes it possible to add HTML elements to the DOM using several methods based on
where you want the new element to be inserted in the DOM:
• append() - Inserts content at the end of the selected elements
• prepend() - Inserts content at the beginning of the selected elements
• after() - Inserts content after the selected elements
• before() - Inserts content before the selected elements
For example, if we wanted to add a new paragraph element with jQuery and append it to the
<body>
<script>
let par = $("<p></p>"); // create a new paragraph element
par.attr("class", "parClass"); // set the class attribute to a class called parClass
par.text("Hello World"); // set the text inside the paragraph to "Hello World"
$(body).append(par); // append the new paragraph to the page body
</script>
9 of 12 11/14/2024, 12:59 PM
Module 7 - Introduction to jQuery: CS 112 : Javascript Prog - Minassian... https://ilearn.laccd.edu/courses/283068/pages/module-7-introduction-to...
It's also possible to add HTML attributes or even other nested HTML while creating a new element
<script>
let par = $("<p class='parClass'><strong>Hello World</strong></p>"); // create a new para
graph element with a predefined class and some HTML inside it.
$(body).append(par); // append the new paragraph to the page body
</script>
Finally, we can "nest" elements using jQuery
<script>
let par = $("<p></p>"); // create a new paragraph element
par.attr("class", "parClass"); // set the class attribute to a class called parClass
let img = $("<img/>"); // create a new image element
img.attr("src", "buildings.png"); // set the image source to a image file
par.append(img); // add the img element to the paragraph element
$(body).append(par); // append the new combined paragraph/image to the page body
</script>
Resulting HTML: <body><p class="parClass"><img src="buildings.png"/></p></body>
11. Removing HTML Elements
jQuery makes it possible to remove HTML elements from the DOM using two methods:
• remove() - Removes the selected element (and its child elements)
• empty() - Removes the child elements from the selected element
For example, if we wanted to remove all images from a page, we can do:
$("#carImg").remove(); // remove an image that has id of 'carImg'
Similarly, we can remove all elements in a containing element. For example
$("#container").empty(); // removes ALL HTML elements from a containing element with id 'con
tainer'
12. CSS Manipula�on
jQuery can be used to work with CSS in the DOM with several methods:
• addClass() - Adds one or more classes to the selected elements
10 of 12 11/14/2024, 12:59 PM
Module 7 - Introduction to jQuery: CS 112 : Javascript Prog - Minassian... https://ilearn.laccd.edu/courses/283068/pages/module-7-introduction-to...
• 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 attribute
We can use jQuery to dynamically add a class to elements:
$("p").addClass("indent"); // Adds the .indent class to all paragraph elements
We can also use the css() method to set or modify a CSS style:
$("p").css("background-color", "gray"); // sets the background color of all paragraph elements to gray
13. Traversing the DOM
Traversing the DOM tree is the method of which you can travel from one element to another
based on the current selected element. jQuery makes it easy to traverse the DOM tree. Before we
explain the terms jQuery uses to define related elements, let's define a few terms:
• Ancestor - Any parent, grandparent, great-grandparent etc. of the selected element.
• Descendant - Any child, grandchild etc. of the selected element.
• Sibling - Any element that shares the same parent.
a. Ancestors
jQuery offers a few methods to access the ancestors of the current selected element:
• parent() - Returns the parent element of the selected element.
• parents() - Returns all the parents of the selected element going up to the body element.
• parentsUntil() - Returns all the parents until a specific element is reached.
For example, if we wanted to set the background-color of a paragraph element when a button
inside is clicked, we can write:
<p>This is a button <button>Click Me!</button></p>
<script>
$("button").parent().css("background-color", "gray");
</script>
b. Descendants
jQuery offers a couple of functions for returning the child elements of the currently selected
11 of 12 11/14/2024, 12:59 PM
Module 7 - Introduction to jQuery: CS 112 : Javascript Prog - Minassian... https://ilearn.laccd.edu/courses/283068/pages/module-7-introduction-to...
element:
• children() - Returns all direct children of the selected element. grandchildren and down are
NOT selected.
• find() - Queries all child elements for a specific selector all the way down to the last
descendant.
For example, we can use the children() method to return all child elements paragraph elements
and remove them:
$("p").children().remove();
c. Siblings
jQuery offers quite a few methods for selecting sibling elements. They are:
• siblings() - Returns all sibling elements of the currently selected element.
• next() - Returns the immediate next element from the currently selected element.
• nextAll() - Returns all element after the currently selected element.
• nextUntil() - Returns all elements after the currently selected element until the specified
element is reached.
• prev() - Returns the immediate previous element from the currently selected element.
• prevAll() - Returns all elements before the currently selected element.
• prevUntil() - Returns all elements before the currently selected element until the specified
element is reached.
For example, the following example shows how to hide a paragraph that comes immediately after
a button:
<button>Hide Paragraph</button>
<p>This paragraph can be hidden</p>
<script>
$("button").on("click", function() {
$(this).next().hide();
});
</script>
14. jQuery AJAX
AJAX with jQuery is covered in a separate document dedicated to the topic.
12 of 12 11/14/2024, 12:59 PM