Lesson 1 - Introduction to jQuery
Welcome to the on-line course about the most popular JavaScript library - jQuery. The library has a simple syntax, greatly simplifies manipulation of page contents, responding to events, animations, and the use of AJAX. However, its greatest strength is probably the vast amount of jQuery plugins, which we can download for our site to get interactive galleries, carousels, extended form elements and so on without putting our own work into it. Although the time of its greatest popularity has already passed, it should still be part of the frontenders' basic knowledge and is still widely used by the most popular frameworks such as the CSS Bootstrap framework itself. Recently, jQuery's competitors are more complex multi-layered frameworks such as Angular or React, but to learn these requires much more effort. This course assumes you know at least basics of JavaScript.
Obtaining jQuery
We can either download the library and upload it on our website or we can
just link to it. We often link to Google where this library is uploaded. It has
a significant advantage since everyone who uses Google (that's a lot of people
by the way) have this library already loaded in the browser's cache. So loading
our site will be both faster and easier for us. We'll paste the following code
into <head>
of our HTML page:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
By this, we have loaded the jQuery library and we can use it now.
Calculator
Because jQuery is really simple, let's start straight with an example. We'll program a calculator that will add 2 numbers entered into a form.
HTML
First, we'll create a simple HTML page in which there'll be the link to
jQuery in <head>
and 2 inputs to enter numbers in
<body>
. The inputs have to have some id
s so we
would be able to select them using jQuery selectors later. The complete page
code might look something like this:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Simple web calculator</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="js/calculator.js" type="text/javascript"></script> </head> <body> <h1>Welcome to a simple calculator!</h1> <input type="text" id="number1" size="5" /> + <input type="text" id="number2" size="5" /><br /> <input type="button" id="button" value="Compute!"> </body> </html>
The HTML code will be rendered in the browser as follows:
We already know that we should always separate JavaScript from the HTML code.
Note that in <head>
we load the calculator.js
file from the js
folder. We're going to place code to handle the
form there. Create the folder and the file.
JavaScript
Now we've to write a script that responds to the click event of the button,
retrieves the values from the inputs, and prints the result. To work with
jQuery, we use the dollar sign - $
. The dollar is actually a
function name chosen in order to write as less code as possible.
Document ready
You surely know that before we run JavaScript code, we should wait for the
HTML page to load. The jQuery library provides the Document Ready event for this
purpose, it usually forms the basis of every script. Let's put the following
code into the js/calculator.js
file:
$(document).ready(function() { // This code will start not before the page is loaded // ... });
The function passed as the parameter of the ready()
function
will not start until the page is loaded. Of course, we could declare the
function above and pass only its name:
function loaded() { // This code will start not before the page is loaded // ... } $(document).ready(loaded);
Since we'll pass some functions to jQuery all the time, we'll declare it directly in parameters because it's shorter.
Let me remind you that it's important to wait for the page to load to be able to work with its elements. If we executed our code before these elements were present in the page, the code wouldn't work.
Selectors and events
Let's proceed further and add the code to handle the form. We'll explain it in a second:
$(document).ready(function() { $("#button").click(function() { var number1 = $("#number1").val(); var number2 = $("#number2").val(); var result = number1 + number2; alert(result); }); });
As you can see, we used the $("#button")
jQuery selector which
says: "select the element with the button
id
". We then
handle its click()
event. Then we pass the handling function which
will be called when the button is clicked. Inside, we create 2 variables to
which we store the contents of the form fields similarly. The selectors select
the elements by their id
s again. The val()
method
returns the contents of these elements, which is the text written in them. You
already know the alert()
function for sure, prints the entered text
as a message.
Trying the app
Test your application in your computer or as the live demo below:
Surely you've figured out that the calculator actually doesn't add numbers,
but it only concatenates them as texts. This is because the numbers came from
the inputs as text and not numbers. So we've to convert them. We'll use the
parseInt()
function, which takes the text as a parameter and
returns it as a number. Modify the line with result computing as follows:
var result = parseInt(number1) + parseInt(number2);
Everything is working as expected:
Congratulations, you've created your first web application in jQuery!
Other events
We start to find that jQuery is based on events. In addition to the core
Document Ready event, which can be also shortened to just $()
, we
also know the click()
event so far, about which we didn't say
everything yet. Let's mention some other events as well:
click()
- It's triggered when clicked with the mouse on an element. It also works on different elements than buttons (e.g. images).dblclick()
- Is triggered on a double-click.change()
- Is triggered when the content of a form element has changed.
The change()
event example:
$(".field").change(function(){ // the response to the change, such as checking whether the specified characters are allowed // to access the element that triggered the event, we use $(this) });
focus()
- Is triggered when a form field gains focus (becomes active).blur()
- Is triggered when a form field looses focus (becomes inactive).
Mouse events
mouseenter()
- Is triggered when the mouse enters an element.mouseleave()
- Is triggered when the mouse leaves an element.
Keyboard events
keydown()
- Is triggered when a specified key is pressed (once).keypress()
- Is triggered when a specified key is being hold (multiple times).keyup()
- Is triggered when the specified key is released (once).
Window events
resize()
- Is triggered when the browser window is resized.scroll()
- Is triggered when the page is scrolled.
All the methods above are actually shorthands and internally call the
bind()
method and pass the name of the event and the callback as
parameters. Events can also be declared as follows:
$(#element_id).bind("click", function() {...});
The syntax above is useful when we don't know to what event we'll react at the time when writing the code. We can pass the event name as string later.
For a complete list of events, see http://api.jquery.com/…gory/events/. During the course, we'll try out more of them.
In the next lesson, Inserting contents in jQuery (DOM), we'll show you how to modify the page contents using jQuery.
Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.
Download
By downloading the following file, you agree to the license terms
Downloaded 2x (1.41 kB)
Application includes source codes in language JavaScript