What is jQuery?
What a JavaScript library is, adding jQuery to a page, the $ function and waiting for the page to be ready.
A shortcut for JavaScript
jQuery is a JavaScript library: a file of ready-made functions you add to your page. Compare hiding every element with the class tip:
// Plain JavaScript
document.querySelectorAll('.tip').forEach(function (el) {
el.style.display = 'none';
});
// jQuery
$('.tip').hide();
jQuery is still JavaScript. Everything you learnt in the JavaScript course still works; jQuery just gives you shorter ways to do common jobs.
Add jQuery to your page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My first jQuery page</title>
</head>
<body>
<h1>Hello!</h1>
<button id="greet">Say hello</button>
<p id="message"></p>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
<script>
$(function () {
$('#greet').on('click', function () {
$('#message').text('Welcome to jQuery!');
});
});
</script>
</body>
</html>
| Piece | Meaning |
|---|---|
| <script src="...jquery.min.js"> | Loads jQuery. It must come before your own script |
| $ | The jQuery function (you can also write jQuery) |
| $(function () { ... }) | Runs your code once the page is ready |
| $('#greet') | Selects the element with id="greet" |
| .on('click', ...) | Runs a function when it is clicked |
| .text('...') | Changes its text |
Exercise
Add a second button "Clear" that empties the message with .text('').
<button id="greet">Say hello</button>
<button id="clear">Clear</button>
<p id="message"></p>
<script>
$(function () {
$('#greet').on('click', function () {
$('#message').text('Welcome to jQuery!');
});
});
</script>
Show a possible solution
<button id="greet">Say hello</button>
<button id="clear">Clear</button>
<p id="message"></p>
<script>
$(function () {
$('#greet').on('click', function () {
$('#message').text('Welcome to jQuery!');
});
$('#clear').on('click', function () {
$('#message').text('');
});
});
</script>
Check your understanding
Quick check
What is jQuery?
Why: It is a file of JavaScript functions.
Quick check
Where must the jQuery script tag go?
Why: $ must exist before you use it.
Quick check
What does $(function () { ... }) do?
Why: It is the ready shortcut.