What is jQuery?

Lesson 1 of 12 18 min read Free lesson

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 vs jQuery Try it in CodeLab
// 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

index.html Try it in CodeLab
<!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>
PieceMeaning
<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('').

Starting code Try it in CodeLab
<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
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?

Quick check

Where must the jQuery script tag go?

Quick check

What does $(function () { ... }) do?

Hi there! đź‘‹ Have a question about the courses or joining the class? Ask me.