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:
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:
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:
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.
Leave a comment