Introduction to jQuery

Now that we've introduced JavaScript functions, let's learn how to use the jQuery library.

To use it, we need to download a single JavaScript file and include in our web page:

  1. How to Download jQuery
  2. How to Include jQuery in a Web Page

Think of jQuery as a handy JavaScript function named $.

If we have an HTML page as follows:

<html>
<head>
  <title>My Page</title>
  <script src="jquery-1.11.2.min.js"></script>
</head>
<body>
  <div id="banana">Banana</div>
  <button id="mybutton">Make it yellow</button>
</body>
</html>

here's what the page looks like:

a webpage with the word Banana and a button that says Make it yellow

Let's use jQuery to make the text background yellow when we click the button.

Create a new JavaScript file (index.js):

$(document).ready(function() {
    $('#mybutton').on('click', function() {
        $('#banana').css('background-color', 'yellow');
    });
});

and include it after jQuery:

<html>
<head>
  <title>My Page</title>
  <script src="jquery-1.11.2.min.js"></script>
  <script src="index.js"></script>
</head>
<body>
  <div id="banana">Banana</div>
  <button id="mybutton">Make it yellow</button>
</body>
</html>

Now, if we reload the page, and click the button, we see:

a webpage with the word Banana, with yellow background color behind the word

Let's explain index.js.

We're using the jQuery function (named $) to find elements on the page and do things with them.

This:

$(document)

sends the document object (a JavaScript object that helps us work with the HTML page) to the $ function, which returns a jQuery object. We then call the ready function on that object:

$(document).ready();

and pass an anonymous function (i.e. one without a name) to the ready function so it will run our code once the document is ready:

$(document).ready(function() {
    //do stuff here
});

We wait until the document is ready because the banana text and button aren't available at the time our index.js file is read by the browser.

This:

$('#mybutton').on('click', function() {
    //do stuff here when the button is clicked
});

uses the $ function to find our button and make stuff happen when the user clicks it.

The # is called a selector. It tells the jQuery function that we're searching for the element by its ID attribute (e.g. mybutton). We call the on() function to tell it what to do when the button is clicked.

This:

$('#banana').css('background-color', 'yellow');

finds the HTML element with the ID banana and sets the background color of the element to yellow.

Comments

Leave a comment

What color are brown eyes? (spam prevention)
Submit
Code under MIT License unless otherwise indicated.
© 2020, Downranked, LLC.