As web developers, we encounter HTML, CSS, and JavaScript fairly early on. As our pages become more complex, the JavaScript required gets more complex to write. That’s where libraries come in. A JavaScript library is a file that contains functions for accomplishing common tasks, reusing code, and simplifying your JavaScript code overall.
jQuery is one of the most popular JavaScript libraries out there. jQuery makes web development easier by overcoming all the “stuff” that makes JavaScript difficult to use. With jQuery, you can call simple methods instead rewriting task blocks.
Any web developer should have jQuery under their belt. So today we will introduce you to the library and show you how to get started.
Today we will cover:
Get introduced to jQuery and learn how to build interactive web pages with animations, visual effects, and advanced functionality.
jQuery is a lightweight, open-source JavaScript library that helps us build interactive web pages with animations, visual effects, and advanced functionality. It is the most popular JavaScript library, used by around 70 million websites worldwide.
The jQuery motto is “write less, do more”, because it reduces many lines of raw JavaScript code into a single line with its simple interface. The main features of jQuery include:
Let’s see how jQuery works to simplify our JavaScript code. Here is a popular manipulation method we use with vanilla JavaScript to load a some paragraphs onto the DOM:
See how it compares to some jQuery that produces the same results. The jQuery library uses JavaScript under the hood to make code more readable.
// Updating the text present in 4 paragraph elements$(document).ready(function() {$("p").html("This is a Paragraph")});
The jQuery library is still one of the most popular libraries seen in legacy code. Its mantra of writing less to do more makes it still a popular library to continue to use today.
jQuery is probably the most popular and extendable JavaScript library. It is used by big companies like Netflix, Google, IBM, and Microsoft. IT is the commonly the first library that JavaScript developers learn because:
Recent advancements in the frontend world with JavaScript frameworks like React and Angular and the fetch API make jQuery a little long in the tooth, but use cases still exist depending on what is needed for your project.
Bootstrap, for the time being, and Wordpress use jQuery to build their components and themes. Many of the big tech companies, while they may not start green field projects with jQuery, still build on ones that started with jQuery. So it’s a good idea to understand jQuery to have it on your resume.
The jQuery library is made up of selectors, event handlers and DOM traversal helpers. Along with Ajax, jQuery does just about everything you need JavaScript to do for your web page. There are three most important elements that make jQuery work are:
$()
or jQuery()
: the $()
exists for the sole purpose of making it so you don’t have to write out jQuery()
every single time you would like to use a selector.selector
: this is how we select our DOM (Document Object Model) element. It’s the element we want to make changes to when the page loads.action()
: this is the function that will tell the DOM what to do. It could be an event listener, it could be an effect depending on use case.Together, a simple jQuery statement is written as:
The
$()
is preferable to thejQuery()
simply because it’s more commonly used. However, both will work.
jQuery uses the Document Object Model (DOM) to manipulate, traverse, and select elements. The HTML document is loaded onto the DOM, where the browser creates a node tree when the page loads. A familial, hierarchical relationship is formed with the elements on the tree where elements are parents, children, and siblings of each other.
jQuery can then manipulate that object tree. We encapsulate all of our jQuery logic with the following selector:
$(document).ready(cb) //cb is a callback function
As you can see, this selector is an instance of the $(selector).action()
syntax we established above. The document on the window object is the selector and the action is the ready()
method. This function will do all the logic that is inside the callback function that is passed as the argument to the method.
Here is a basic Hello World example of loading and manipulating the DOM with jQuery:
<html><head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script></head><body><div><h1> </h1><div></body></html>
$(document).ready(() => {$("h1").html("Hello World");});
This course will introduce you to jQuery, a framework for building interactive web pages with animations, visual effects, and advanced functionality. You will start with a brief introduction to the course and jQuery. Work on an interactive project throughout the course with quizzes and challenges.
In the same way that CSS Selectors find HTML elements to apply style, jQuery selectors find DOM elements to apply effects or events listeners. We use the $()
function with a string passed in that identifies the specific element(s) in some way.
Some of the ways we can select elements:
When you select by tag name, use HTML tag names such as div or h1 as seen in the Hello World example above.
Use the familiar CSS syntax you use when selecting an element by id to grab a DOM element in jQuery:
<html><head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script></head><body><div id="logo"><img src="http://placekitten.com/300/300" alt="placekitten"/><div></body></html>
$(document).ready(() => {$('#logo').append('kittty catttt!'); //appending text to div element with id=logo});
In the code snippet, the text is only appended to the
div
with anid
oflogo
.
As with CSS, we can also select elements by their class name. Use a ‘.’ in front of the class name to select this element:
<html><head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script></head><body><div id="logo"><p class="example-1"></p><p class="example-1"></p><p class="example-1"></p><p class="example-1"></p><div></body></html>
$(document).ready(() => {$('.example-1').append('this is a paragraph');//appending text to div element with class= “example-1”});
In the code snippet, the text is appended to every
element
with a class ofexample-1
.
Selection by attribute and attribute value exists as well. Use square brackets [ ]
to select those elements:
<html><head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script></head><body><div id="logo"><p class="example-1" id="red"></p><p class="example-1" id="blue"></p><p class="example-1" id="yellow"></p><p class="example-1" id="green"></p><div></body></html>
$(document).ready(function () {$('.example-1').append("This is a paragraph element'");$('[id = "red"]').css("color", "red");$('[id = "green"]').css("color", "green");$('[id = "yellow"]').css("color", "yellow");$('[id = "blue"]').css("color", "blue");$('[class]').css({"background":"lightgray", padding: '20px'});});
Creating new elements in jQuery is as simple as using the $()
function:
$(document).ready(function () {
var newDiv = $("<div>") // Create an empty div element
var newListItem = $("<li> ab </li>") // Create list element with content "ab"
});
This only creates the element. It does not add it to the DOM. We need to do a separate action for adding it to the web page.
At a high level, an action or an event handler is a function that is triggered by a user’s interaction with your web page. In jQuery, there are all kinds of events that can be used to trigger an event handler: mouse, keyboard, form, and more!
It is the responsibility of the event handler to listen for a particular event on a given element. As soon as the user interacts with that element, an event handler is fired that performs the logic in that function.
In jQuery, we use the familiar $(“selector”).action()
syntax as the basis for our handler:
<html><head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script></head><body><div><button> Click Me </button><div></body></html>
$(document).ready(() => {$("button").click((event) => {alert("Button clicked by user!");});});
The selector is chosen as we have done before. The action is the actual event that we are listening for on the element that is selected. Here, the button
tag is listening for a click event. When the button
is clicked, it will alert the user.
Try logging to your console the event
. The event object is full of different properties that could prove useful in your logic. This object is included by default to all event handlers.
To utilize jQuery, you need to have a link to the library in your project. There are three ways that you can do that.
<head>
<script src="link-to-library"> </script>
</head>
package.json
file, install the jQuery package:// npm
install jquery
//yarn
yarn add jquery
<head>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
</head>
Try your hand at setting up a simple jQuery application. If you get stuck, there is a solution provided to help guide your process.
We will take the first step to building a simple jQuery To Do list application. This portion of the program should assign a click event handler to the add button and generate an alert displaying the task added in the text box.
To add a task in our to-do list web page, the user enters a new task in a text box and then clicks on the add button. The task in this challenge is as follows:
click
event handler to the add button with an id
of addTask
.alert
with the text “Error: Please enter a task before clicking the Add button”.alert
with the text containing the task name. For example, if the text in the input box is “Complete Assignment”, generate an alert
with text “New Task: Complete Assignment”.Note: The current value of the input box can be accessed using
$("selector").val()
.Additionally, the text present in the text box can be cleared out using
$("selector").val("")
.
Sample Input: Enter “Complete Assignment” in the text box and click the add button.
Sample Output: An alert
with the text “New Task: Complete Assignment” is generated and the text box is cleared out.
Try it out below for checking the solution!
addTask
. The button class is already assigned in the web page HTML.textBox
using $(".textBox").val()
. The text box class is also assigned in the web page HTML.alert
with the task on line 4 and clear out the text box in line 5.alert
with the text “Error: Please enter a task before clicking the Add button” on line 8.Congrats! You are now familiar with jQuery and have created your own first step to building a functioning application. Your next steps are:
At this point, you are ready to tackle our course, The Complete Guide to jQuery. In this course, you will continue your jQuery journey with more event handling, animations, DOM traversal and manipulation, and AJAX methods. You will be working on an interactive project throughout the course with quizzes and challenges at the end of each chapter.
Happy learning!
Free Resources